| Differences between
and this patch
- a/Source/WebCore/ChangeLog +35 lines
Lines 1-3 a/Source/WebCore/ChangeLog_sec1
1
2020-06-19  Yusuke Suzuki  <ysuzuki@apple.com>
2
3
        JS Modules in Workers
4
        https://bugs.webkit.org/show_bug.cgi?id=164860
5
6
        Reviewed by NOBODY (OOPS!).
7
8
        No new tests (OOPS!).
9
10
        * bindings/js/WorkerScriptController.cpp:
11
        (WebCore::WorkerScriptController::loadModuleSynchronously):
12
        (WebCore::WorkerScriptController::linkAndEvaluateModule):
13
        * bindings/js/WorkerScriptController.h:
14
        * dom/LoadableModuleScript.cpp:
15
        (WebCore::LoadableModuleScript::load): Deleted.
16
        * dom/LoadableModuleScript.h:
17
        * dom/ScriptElement.cpp:
18
        (WebCore::ScriptElement::requestModuleScript):
19
        * workers/Worker.cpp:
20
        (WebCore::Worker::Worker):
21
        (WebCore::Worker::create):
22
        (WebCore::Worker::notifyFinished):
23
        * workers/Worker.h:
24
        * workers/Worker.idl:
25
        * workers/WorkerGlobalScopeProxy.h:
26
        * workers/WorkerMessagingProxy.cpp:
27
        (WebCore::WorkerMessagingProxy::startWorkerGlobalScope):
28
        * workers/WorkerMessagingProxy.h:
29
        * workers/WorkerThread.cpp:
30
        (WebCore::WorkerParameters::isolatedCopy const):
31
        (WebCore::WorkerThread::workerThread):
32
        * workers/WorkerThread.h:
33
        * workers/service/context/ServiceWorkerThread.cpp:
34
        (WebCore::ServiceWorkerThread::ServiceWorkerThread):
35
1
2020-06-18  Doug Kelly  <dougk@apple.com>
36
2020-06-18  Doug Kelly  <dougk@apple.com>
2
37
3
        Use paintCellAndSetFocusedElementNeedsRepaintIfNecessary() for search field buttons
38
        Use paintCellAndSetFocusedElementNeedsRepaintIfNecessary() for search field buttons
- a/Source/WebCore/bindings/js/WorkerScriptController.cpp +111 lines
Lines 32-37 a/Source/WebCore/bindings/js/WorkerScriptController.cpp_sec1
32
#include "JSEventTarget.h"
32
#include "JSEventTarget.h"
33
#include "JSExecState.h"
33
#include "JSExecState.h"
34
#include "JSServiceWorkerGlobalScope.h"
34
#include "JSServiceWorkerGlobalScope.h"
35
#include "LoadableModuleScript.h"
36
#include "ModuleFetchParameters.h"
35
#include "ScriptSourceCode.h"
37
#include "ScriptSourceCode.h"
36
#include "WebCoreJSClientData.h"
38
#include "WebCoreJSClientData.h"
37
#include "WorkerConsoleClient.h"
39
#include "WorkerConsoleClient.h"
Lines 174-179 void WorkerScriptController::evaluate(const ScriptSourceCode& sourceCode, NakedP a/Source/WebCore/bindings/js/WorkerScriptController.cpp_sec2
174
    }
176
    }
175
}
177
}
176
178
179
MessageQueueWaitResult WorkerScriptController::loadModuleSynchronously(LoadableModuleScript& moduleScript, const ScriptSourceCode& sourceCode)
180
{
181
    if (isExecutionForbidden())
182
        return MessageQueueTerminated;
183
184
    initScriptIfNeeded();
185
186
    auto& lexicalGlobalObject = *m_workerGlobalScopeWrapper.get();
187
    VM& vm = lexicalGlobalObject.vm();
188
    JSLockHolder lock { vm };
189
190
    auto& promise = JSExecState::loadModule(lexicalGlobalObject, sourceCode.jsSourceCode(), JSC::JSScriptFetcher::create(vm, { &moduleScript }));
191
192
    RefPtr<LoadableModuleScript> moduleScriptRef(&moduleScript);
193
194
    auto& fulfillHandler = *JSNativeStdFunction::create(vm, &lexicalGlobalObject, 1, String(), [moduleScriptRef](JSGlobalObject* globalObject, CallFrame* callFrame) -> JSC::EncodedJSValue {
195
        VM& vm = globalObject->vm();
196
        auto scope = DECLARE_THROW_SCOPE(vm);
197
        Identifier moduleKey = jsValueToModuleKey(globalObject, callFrame->argument(0));
198
        RETURN_IF_EXCEPTION(scope, { });
199
        moduleScriptRef->notifyLoadCompleted(*moduleKey.impl());
200
        return JSValue::encode(jsUndefined());
201
    });
202
203
    auto& rejectHandler = *JSNativeStdFunction::create(vm, &lexicalGlobalObject, 1, String(), [moduleScriptRef](JSGlobalObject* globalObject, CallFrame* callFrame) {
204
        VM& vm = globalObject->vm();
205
        JSValue errorValue = callFrame->argument(0);
206
        if (errorValue.isObject()) {
207
            auto* object = JSC::asObject(errorValue);
208
            if (JSValue failureKindValue = object->getDirect(vm, static_cast<JSVMClientData&>(*vm.clientData).builtinNames().failureKindPrivateName())) {
209
                // This is host propagated error in the module loader pipeline.
210
                switch (static_cast<ModuleFetchFailureKind>(failureKindValue.asInt32())) {
211
                case ModuleFetchFailureKind::WasErrored:
212
                    moduleScriptRef->notifyLoadFailed(LoadableScript::Error {
213
                        LoadableScript::ErrorType::CachedScript,
214
                        WTF::nullopt
215
                    });
216
                    break;
217
                case ModuleFetchFailureKind::WasCanceled:
218
                    moduleScriptRef->notifyLoadWasCanceled();
219
                    break;
220
                }
221
                return JSValue::encode(jsUndefined());
222
            }
223
        }
224
225
        auto scope = DECLARE_CATCH_SCOPE(vm);
226
        moduleScriptRef->notifyLoadFailed(LoadableScript::Error {
227
            LoadableScript::ErrorType::CachedScript,
228
            LoadableScript::ConsoleMessage {
229
                MessageSource::JS,
230
                MessageLevel::Error,
231
                retrieveErrorMessage(*globalObject, vm, errorValue, scope),
232
            }
233
        });
234
        return JSValue::encode(jsUndefined());
235
    });
236
237
    promise.then(&lexicalGlobalObject, &fulfillHandler, &rejectHandler);
238
239
    // Drive RunLoop until we get either of "Worker is terminated", "Loading is done", or "Loading is failed".
240
    WorkerRunLoop& runLoop = m_workerGlobalScope->thread().runLoop();
241
    String mode = makeString("loadModuleSynchronously", runLoop.createUniqueId());
242
243
    MessageQueueWaitResult result = MessageQueueMessageReceived;
244
    while ((!moduleScriptRef->isLoaded() || !moduleScriptRef->wasCanceled()) && result != MessageQueueTerminated)
245
        result = runLoop.runInMode(m_workerGlobalScope, mode);
246
247
    // FIXME: Currently we are not offering cancelling.
248
    // if (!loader->done() && result == MessageQueueTerminated)
249
    //     loader->cancel();
250
251
    return result;
252
}
253
254
void WorkerScriptController::linkAndEvaluateModule(LoadableModuleScript& moduleScript, const ScriptSourceCode& sourceCode, String* returnedExceptionMessage)
255
{
256
    if (isExecutionForbidden())
257
        return;
258
259
    initScriptIfNeeded();
260
261
    auto& lexicalGlobalObject = *m_workerGlobalScopeWrapper.get();
262
    VM& vm = lexicalGlobalObject.vm();
263
    JSLockHolder lock { vm };
264
265
    NakedPtr<JSC::Exception> returnedException;
266
    JSExecState::linkAndEvaluateModule(lexicalGlobalObject, Identifier::fromUid(vm, moduleScript.moduleKey()), jsUndefined(), returnedException);
267
    if ((returnedException && isTerminatedExecutionException(vm, returnedException)) || isTerminatingExecution()) {
268
        forbidExecution();
269
        return;
270
    }
271
272
    if (returnedException) {
273
        if (m_workerGlobalScope->canIncludeErrorDetails(sourceCode.cachedScript(), sourceCode.url().string())) {
274
            // FIXME: It's not great that this can run arbitrary code to string-ify the value of the exception.
275
            // Do we need to do anything to handle that properly, if it, say, raises another exception?
276
            if (returnedExceptionMessage)
277
                *returnedExceptionMessage = returnedException->value().toWTFString(&lexicalGlobalObject);
278
        } else {
279
            // Overwrite the detailed error with a generic error.
280
            String genericErrorMessage { "Script error."_s };
281
            if (returnedExceptionMessage)
282
                *returnedExceptionMessage = genericErrorMessage;
283
            returnedException = JSC::Exception::create(vm, createError(&lexicalGlobalObject, genericErrorMessage));
284
        }
285
    }
286
}
287
177
void WorkerScriptController::setException(JSC::Exception* exception)
288
void WorkerScriptController::setException(JSC::Exception* exception)
178
{
289
{
179
    JSC::JSGlobalObject* lexicalGlobalObject = m_workerGlobalScopeWrapper.get();
290
    JSC::JSGlobalObject* lexicalGlobalObject = m_workerGlobalScopeWrapper.get();
- a/Source/WebCore/bindings/js/WorkerScriptController.h +5 lines
Lines 31-36 a/Source/WebCore/bindings/js/WorkerScriptController.h_sec1
31
#include <JavaScriptCore/Strong.h>
31
#include <JavaScriptCore/Strong.h>
32
#include <wtf/Forward.h>
32
#include <wtf/Forward.h>
33
#include <wtf/Lock.h>
33
#include <wtf/Lock.h>
34
#include <wtf/MessageQueue.h>
34
#include <wtf/NakedPtr.h>
35
#include <wtf/NakedPtr.h>
35
36
36
namespace JSC {
37
namespace JSC {
Lines 40-45 class VM; a/Source/WebCore/bindings/js/WorkerScriptController.h_sec2
40
namespace WebCore {
41
namespace WebCore {
41
42
42
class JSWorkerGlobalScope;
43
class JSWorkerGlobalScope;
44
class LoadableModuleScript;
43
class ScriptSourceCode;
45
class ScriptSourceCode;
44
class WorkerConsoleClient;
46
class WorkerConsoleClient;
45
class WorkerGlobalScope;
47
class WorkerGlobalScope;
Lines 58-63 class WorkerScriptController { a/Source/WebCore/bindings/js/WorkerScriptController.h_sec3
58
60
59
    void evaluate(const ScriptSourceCode&, String* returnedExceptionMessage = nullptr);
61
    void evaluate(const ScriptSourceCode&, String* returnedExceptionMessage = nullptr);
60
    void evaluate(const ScriptSourceCode&, NakedPtr<JSC::Exception>& returnedException, String* returnedExceptionMessage = nullptr);
62
    void evaluate(const ScriptSourceCode&, NakedPtr<JSC::Exception>& returnedException, String* returnedExceptionMessage = nullptr);
63
    void linkAndEvaluateModule(LoadableModuleScript&, const ScriptSourceCode& sourceCode, String* returnedExceptionMessage = nullptr);
64
65
    MessageQueueWaitResult loadModuleSynchronously(LoadableModuleScript&, const ScriptSourceCode&);
61
66
62
    void setException(JSC::Exception*);
67
    void setException(JSC::Exception*);
63
68
- a/Source/WebCore/dom/LoadableModuleScript.cpp -12 lines
Lines 88-103 void LoadableModuleScript::execute(ScriptElement& scriptElement) a/Source/WebCore/dom/LoadableModuleScript.cpp_sec1
88
    scriptElement.executeModuleScript(*this);
88
    scriptElement.executeModuleScript(*this);
89
}
89
}
90
90
91
void LoadableModuleScript::load(Document& document, const URL& rootURL)
92
{
93
    if (auto* frame = document.frame())
94
        frame->script().loadModuleScript(*this, rootURL.string(), m_parameters.copyRef());
95
}
96
97
void LoadableModuleScript::load(Document& document, const ScriptSourceCode& sourceCode)
98
{
99
    if (auto* frame = document.frame())
100
        frame->script().loadModuleScript(*this, sourceCode);
101
}
102
103
}
91
}
- a/Source/WebCore/dom/LoadableModuleScript.h -3 / +2 lines
Lines 50-64 class LoadableModuleScript final : public LoadableScript { a/Source/WebCore/dom/LoadableModuleScript.h_sec1
50
50
51
    void setError(Error&&);
51
    void setError(Error&&);
52
52
53
    void load(Document&, const URL& rootURL);
54
    void load(Document&, const ScriptSourceCode&);
55
56
    void notifyLoadCompleted(UniquedStringImpl&);
53
    void notifyLoadCompleted(UniquedStringImpl&);
57
    void notifyLoadFailed(LoadableScript::Error&&);
54
    void notifyLoadFailed(LoadableScript::Error&&);
58
    void notifyLoadWasCanceled();
55
    void notifyLoadWasCanceled();
59
56
60
    UniquedStringImpl* moduleKey() const { return m_moduleKey.get(); }
57
    UniquedStringImpl* moduleKey() const { return m_moduleKey.get(); }
61
58
59
    ModuleFetchParameters& parameters() { return m_parameters.get(); }
60
62
private:
61
private:
63
    LoadableModuleScript(const String& nonce, const String& integrity, ReferrerPolicy, const String& crossOriginMode, const String& charset, const AtomString& initiatorName, bool isInUserAgentShadowTree);
62
    LoadableModuleScript(const String& nonce, const String& integrity, ReferrerPolicy, const String& crossOriginMode, const String& charset, const AtomString& initiatorName, bool isInUserAgentShadowTree);
64
63
- a/Source/WebCore/dom/ScriptElement.cpp -2 / +7 lines
Lines 42-47 a/Source/WebCore/dom/ScriptElement.cpp_sec1
42
#include "LoadableClassicScript.h"
42
#include "LoadableClassicScript.h"
43
#include "LoadableModuleScript.h"
43
#include "LoadableModuleScript.h"
44
#include "MIMETypeRegistry.h"
44
#include "MIMETypeRegistry.h"
45
#include "ModuleFetchParameters.h"
45
#include "PendingScript.h"
46
#include "PendingScript.h"
46
#include "RuntimeApplicationChecks.h"
47
#include "RuntimeApplicationChecks.h"
47
#include "SVGScriptElement.h"
48
#include "SVGScriptElement.h"
Lines 351-358 bool ScriptElement::requestModuleScript(const TextPosition& scriptStartPosition) a/Source/WebCore/dom/ScriptElement.cpp_sec2
351
            scriptCharset(),
352
            scriptCharset(),
352
            m_element.localName(),
353
            m_element.localName(),
353
            m_element.isInUserAgentShadowTree());
354
            m_element.isInUserAgentShadowTree());
354
        script->load(m_element.document(), moduleScriptRootURL);
355
        m_loadableScript = WTFMove(script);
355
        m_loadableScript = WTFMove(script);
356
        if (auto* frame = m_element.document().frame()) {
357
            auto& script = downcast<LoadableModuleScript>(*m_loadableScript.get());
358
            frame->script().loadModuleScript(script, moduleScriptRootURL.string(), makeRef(script.parameters()));
359
        }
356
        return true;
360
        return true;
357
    }
361
    }
358
362
Lines 367-374 bool ScriptElement::requestModuleScript(const TextPosition& scriptStartPosition) a/Source/WebCore/dom/ScriptElement.cpp_sec3
367
    if (!contentSecurityPolicy.allowInlineScript(m_element.document().url().string(), m_startLineNumber, sourceCode.source().toStringWithoutCopying(), hasKnownNonce))
371
    if (!contentSecurityPolicy.allowInlineScript(m_element.document().url().string(), m_startLineNumber, sourceCode.source().toStringWithoutCopying(), hasKnownNonce))
368
        return false;
372
        return false;
369
373
370
    script->load(m_element.document(), sourceCode);
371
    m_loadableScript = WTFMove(script);
374
    m_loadableScript = WTFMove(script);
375
    if (auto* frame = m_element.document().frame())
376
        frame->script().loadModuleScript(downcast<LoadableModuleScript>(*m_loadableScript.get()), sourceCode);
372
    return true;
377
    return true;
373
}
378
}
374
379
- a/Source/WebCore/workers/Worker.cpp -2 / +7 lines
Lines 69-74 inline Worker::Worker(ScriptExecutionContext& context, JSC::RuntimeFlags runtime a/Source/WebCore/workers/Worker.cpp_sec1
69
    , m_identifier("worker:" + Inspector::IdentifiersFactory::createIdentifier())
69
    , m_identifier("worker:" + Inspector::IdentifiersFactory::createIdentifier())
70
    , m_contextProxy(WorkerGlobalScopeProxy::create(*this))
70
    , m_contextProxy(WorkerGlobalScopeProxy::create(*this))
71
    , m_runtimeFlags(runtimeFlags)
71
    , m_runtimeFlags(runtimeFlags)
72
    , m_type(options.type)
73
    , m_credentials(options.credentials)
72
{
74
{
73
    static bool addedListener;
75
    static bool addedListener;
74
    if (!addedListener) {
76
    if (!addedListener) {
Lines 112-121 ExceptionOr<Ref<Worker>> Worker::create(ScriptExecutionContext& context, JSC::Ru a/Source/WebCore/workers/Worker.cpp_sec2
112
114
113
    FetchOptions fetchOptions;
115
    FetchOptions fetchOptions;
114
    fetchOptions.mode = FetchOptions::Mode::SameOrigin;
116
    fetchOptions.mode = FetchOptions::Mode::SameOrigin;
117
    if (worker->m_type == WorkerType::Module)
118
        fetchOptions.credentials = worker->m_credentials;
115
    fetchOptions.cache = FetchOptions::Cache::Default;
119
    fetchOptions.cache = FetchOptions::Cache::Default;
116
    fetchOptions.redirect = FetchOptions::Redirect::Follow;
120
    fetchOptions.redirect = FetchOptions::Redirect::Follow;
117
    fetchOptions.destination = FetchOptions::Destination::Worker;
121
    fetchOptions.destination = FetchOptions::Destination::Worker;
118
    worker->m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(fetchOptions), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, worker);
122
    worker->m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(fetchOptions), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, worker.get());
123
119
    return worker;
124
    return worker;
120
}
125
}
121
126
Lines 214-220 void Worker::notifyFinished() a/Source/WebCore/workers/Worker.cpp_sec3
214
    ReferrerPolicy referrerPolicy = ReferrerPolicy::EmptyString;
219
    ReferrerPolicy referrerPolicy = ReferrerPolicy::EmptyString;
215
    if (auto policy = parseReferrerPolicy(m_scriptLoader->referrerPolicy(), ReferrerPolicySource::HTTPHeader))
220
    if (auto policy = parseReferrerPolicy(m_scriptLoader->referrerPolicy(), ReferrerPolicySource::HTTPHeader))
216
        referrerPolicy = *policy;
221
        referrerPolicy = *policy;
217
    m_contextProxy.startWorkerGlobalScope(m_scriptLoader->url(), m_name, context->userAgent(m_scriptLoader->url()), isOnline, m_scriptLoader->script(), contentSecurityPolicyResponseHeaders, m_shouldBypassMainWorldContentSecurityPolicy, m_workerCreationTime, referrerPolicy, m_runtimeFlags);
222
    m_contextProxy.startWorkerGlobalScope(m_scriptLoader->url(), m_name, context->userAgent(m_scriptLoader->url()), isOnline, m_scriptLoader->script(), contentSecurityPolicyResponseHeaders, m_shouldBypassMainWorldContentSecurityPolicy, m_workerCreationTime, referrerPolicy, m_type, m_credentials, m_runtimeFlags);
218
    InspectorInstrumentation::scriptImported(*context, m_scriptLoader->identifier(), m_scriptLoader->script());
223
    InspectorInstrumentation::scriptImported(*context, m_scriptLoader->identifier(), m_scriptLoader->script());
219
}
224
}
220
225
- a/Source/WebCore/workers/Worker.h +8 lines
Lines 29-37 a/Source/WebCore/workers/Worker.h_sec1
29
#include "ActiveDOMObject.h"
29
#include "ActiveDOMObject.h"
30
#include "ContentSecurityPolicyResponseHeaders.h"
30
#include "ContentSecurityPolicyResponseHeaders.h"
31
#include "EventTarget.h"
31
#include "EventTarget.h"
32
#include "FetchRequestCredentials.h"
32
#include "MessagePort.h"
33
#include "MessagePort.h"
33
#include "PostMessageOptions.h"
34
#include "PostMessageOptions.h"
34
#include "WorkerScriptLoaderClient.h"
35
#include "WorkerScriptLoaderClient.h"
36
#include "WorkerType.h"
35
#include <JavaScriptCore/RuntimeFlags.h>
37
#include <JavaScriptCore/RuntimeFlags.h>
36
#include <wtf/MonotonicTime.h>
38
#include <wtf/MonotonicTime.h>
37
#include <wtf/Optional.h>
39
#include <wtf/Optional.h>
Lines 53-58 class Worker final : public AbstractWorker, public ActiveDOMObject, private Work a/Source/WebCore/workers/Worker.h_sec2
53
    WTF_MAKE_ISO_ALLOCATED(Worker);
55
    WTF_MAKE_ISO_ALLOCATED(Worker);
54
public:
56
public:
55
    struct Options {
57
    struct Options {
58
        WorkerType type;
59
        FetchRequestCredentials credentials;
56
        String name;
60
        String name;
57
    };
61
    };
58
    static ExceptionOr<Ref<Worker>> create(ScriptExecutionContext&, JSC::RuntimeFlags, const String& url, const Options&);
62
    static ExceptionOr<Ref<Worker>> create(ScriptExecutionContext&, JSC::RuntimeFlags, const String& url, const Options&);
Lines 70-75 class Worker final : public AbstractWorker, public ActiveDOMObject, private Work a/Source/WebCore/workers/Worker.h_sec3
70
74
71
    void dispatchEvent(Event&) final;
75
    void dispatchEvent(Event&) final;
72
76
77
    WorkerType type() const { return m_type; }
78
73
private:
79
private:
74
    explicit Worker(ScriptExecutionContext&, JSC::RuntimeFlags, const Options&);
80
    explicit Worker(ScriptExecutionContext&, JSC::RuntimeFlags, const Options&);
75
81
Lines 100-105 class Worker final : public AbstractWorker, public ActiveDOMObject, private Work a/Source/WebCore/workers/Worker.h_sec4
100
    JSC::RuntimeFlags m_runtimeFlags;
106
    JSC::RuntimeFlags m_runtimeFlags;
101
    Deque<RefPtr<Event>> m_pendingEvents;
107
    Deque<RefPtr<Event>> m_pendingEvents;
102
    bool m_wasTerminated { false };
108
    bool m_wasTerminated { false };
109
    WorkerType m_type { WorkerType::Classic };
110
    FetchRequestCredentials m_credentials { FetchRequestCredentials::SameOrigin };
103
};
111
};
104
112
105
} // namespace WebCore
113
} // namespace WebCore
- a/Source/WebCore/workers/Worker.idl +2 lines
Lines 37-42 a/Source/WebCore/workers/Worker.idl_sec1
37
};
37
};
38
38
39
dictionary WorkerOptions {
39
dictionary WorkerOptions {
40
    WorkerType type = "classic";
41
    FetchRequestCredentials credentials = "same-origin"; // credentials is only used if type is "module"
40
    DOMString name = "";
42
    DOMString name = "";
41
};
43
};
42
44
- a/Source/WebCore/workers/WorkerGlobalScopeProxy.h -1 / +1 lines
Lines 46-52 class WorkerGlobalScopeProxy { a/Source/WebCore/workers/WorkerGlobalScopeProxy.h_sec1
46
public:
46
public:
47
    static WorkerGlobalScopeProxy& create(Worker&);
47
    static WorkerGlobalScopeProxy& create(Worker&);
48
48
49
    virtual void startWorkerGlobalScope(const URL& scriptURL, const String& name, const String& userAgent, bool isOnline, const String& sourceCode, const ContentSecurityPolicyResponseHeaders&, bool shouldBypassMainWorldContentSecurityPolicy, MonotonicTime timeOrigin, ReferrerPolicy, JSC::RuntimeFlags) = 0;
49
    virtual void startWorkerGlobalScope(const URL& scriptURL, const String& name, const String& userAgent, bool isOnline, const String& sourceCode, const ContentSecurityPolicyResponseHeaders&, bool shouldBypassMainWorldContentSecurityPolicy, MonotonicTime timeOrigin, ReferrerPolicy, WorkerType workerType, FetchRequestCredentials credentials, JSC::RuntimeFlags) = 0;
50
    virtual void terminateWorkerGlobalScope() = 0;
50
    virtual void terminateWorkerGlobalScope() = 0;
51
    virtual void postMessageToWorkerGlobalScope(MessageWithMessagePorts&&) = 0;
51
    virtual void postMessageToWorkerGlobalScope(MessageWithMessagePorts&&) = 0;
52
    virtual bool hasPendingActivity() const = 0;
52
    virtual bool hasPendingActivity() const = 0;
- a/Source/WebCore/workers/WorkerMessagingProxy.cpp -2 / +2 lines
Lines 73-79 WorkerMessagingProxy::~WorkerMessagingProxy() a/Source/WebCore/workers/WorkerMessagingProxy.cpp_sec1
73
        || (is<WorkerGlobalScope>(*m_scriptExecutionContext) && downcast<WorkerGlobalScope>(*m_scriptExecutionContext).thread().thread() == &Thread::current()));
73
        || (is<WorkerGlobalScope>(*m_scriptExecutionContext) && downcast<WorkerGlobalScope>(*m_scriptExecutionContext).thread().thread() == &Thread::current()));
74
}
74
}
75
75
76
void WorkerMessagingProxy::startWorkerGlobalScope(const URL& scriptURL, const String& name, const String& userAgent, bool isOnline, const String& sourceCode, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders, bool shouldBypassMainWorldContentSecurityPolicy, MonotonicTime timeOrigin, ReferrerPolicy referrerPolicy, JSC::RuntimeFlags runtimeFlags)
76
void WorkerMessagingProxy::startWorkerGlobalScope(const URL& scriptURL, const String& name, const String& userAgent, bool isOnline, const String& sourceCode, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders, bool shouldBypassMainWorldContentSecurityPolicy, MonotonicTime timeOrigin, ReferrerPolicy referrerPolicy, WorkerType workerType, FetchRequestCredentials credentials, JSC::RuntimeFlags runtimeFlags)
77
{
77
{
78
    // FIXME: This need to be revisited when we support nested worker one day
78
    // FIXME: This need to be revisited when we support nested worker one day
79
    ASSERT(m_scriptExecutionContext);
79
    ASSERT(m_scriptExecutionContext);
Lines 89-95 void WorkerMessagingProxy::startWorkerGlobalScope(const URL& scriptURL, const St a/Source/WebCore/workers/WorkerMessagingProxy.cpp_sec2
89
89
90
    SocketProvider* socketProvider = document.socketProvider();
90
    SocketProvider* socketProvider = document.socketProvider();
91
91
92
    WorkerParameters params = { scriptURL, name, identifier, userAgent, isOnline, contentSecurityPolicyResponseHeaders, shouldBypassMainWorldContentSecurityPolicy, timeOrigin, referrerPolicy, document.settings().requestAnimationFrameEnabled() };
92
    WorkerParameters params = { scriptURL, name, identifier, userAgent, isOnline, contentSecurityPolicyResponseHeaders, shouldBypassMainWorldContentSecurityPolicy, timeOrigin, referrerPolicy, workerType, credentials, document.settings().requestAnimationFrameEnabled() };
93
    auto thread = DedicatedWorkerThread::create(params, sourceCode, *this, *this, *this, startMode, document.topOrigin(), proxy, socketProvider, runtimeFlags);
93
    auto thread = DedicatedWorkerThread::create(params, sourceCode, *this, *this, *this, startMode, document.topOrigin(), proxy, socketProvider, runtimeFlags);
94
94
95
    workerThreadCreated(thread.get());
95
    workerThreadCreated(thread.get());
- a/Source/WebCore/workers/WorkerMessagingProxy.h -1 / +1 lines
Lines 50-56 class WorkerMessagingProxy final : public ThreadSafeRefCounted<WorkerMessagingPr a/Source/WebCore/workers/WorkerMessagingProxy.h_sec1
50
private:
50
private:
51
    // Implementations of WorkerGlobalScopeProxy.
51
    // Implementations of WorkerGlobalScopeProxy.
52
    // (Only use these functions in the worker object thread.)
52
    // (Only use these functions in the worker object thread.)
53
    void startWorkerGlobalScope(const URL& scriptURL, const String& name, const String& userAgent, bool isOnline, const String& sourceCode, const ContentSecurityPolicyResponseHeaders&, bool shouldBypassMainWorldContentSecurityPolicy, MonotonicTime timeOrigin, ReferrerPolicy, JSC::RuntimeFlags) final;
53
    void startWorkerGlobalScope(const URL& scriptURL, const String& name, const String& userAgent, bool isOnline, const String& sourceCode, const ContentSecurityPolicyResponseHeaders&, bool shouldBypassMainWorldContentSecurityPolicy, MonotonicTime timeOrigin, ReferrerPolicy, WorkerType workerType, FetchRequestCredentials credentials, JSC::RuntimeFlags) final;
54
    void terminateWorkerGlobalScope() final;
54
    void terminateWorkerGlobalScope() final;
55
    void postMessageToWorkerGlobalScope(MessageWithMessagePorts&&) final;
55
    void postMessageToWorkerGlobalScope(MessageWithMessagePorts&&) final;
56
    bool hasPendingActivity() const final;
56
    bool hasPendingActivity() const final;
- a/Source/WebCore/workers/WorkerThread.cpp -3 / +29 lines
Lines 28-33 a/Source/WebCore/workers/WorkerThread.cpp_sec1
28
#include "WorkerThread.h"
28
#include "WorkerThread.h"
29
29
30
#include "IDBConnectionProxy.h"
30
#include "IDBConnectionProxy.h"
31
#include "LoadableModuleScript.h"
31
#include "ScriptSourceCode.h"
32
#include "ScriptSourceCode.h"
32
#include "SecurityOrigin.h"
33
#include "SecurityOrigin.h"
33
#include "SocketProvider.h"
34
#include "SocketProvider.h"
Lines 81-86 WorkerParameters WorkerParameters::isolatedCopy() const a/Source/WebCore/workers/WorkerThread.cpp_sec2
81
        shouldBypassMainWorldContentSecurityPolicy,
82
        shouldBypassMainWorldContentSecurityPolicy,
82
        timeOrigin,
83
        timeOrigin,
83
        referrerPolicy,
84
        referrerPolicy,
85
        workerType,
86
        credentials,
84
        requestAnimationFrameEnabled,
87
        requestAnimationFrameEnabled,
85
    };
88
    };
86
}
89
}
Lines 191-200 void WorkerThread::workerThread() a/Source/WebCore/workers/WorkerThread.cpp_sec3
191
            scriptController->forbidExecution();
194
            scriptController->forbidExecution();
192
    }
195
    }
193
196
194
    String exceptionMessage;
197
    // We are currently holding only the initial script code. If the WorkerType is Module, we should fetch the entire graph before executing the rest of this.
195
    scriptController->evaluate(ScriptSourceCode(m_startupData->sourceCode, URL(m_startupData->params.scriptURL)), &exceptionMessage);
198
    // We invoke module loader as if we are executing inline module script tag in Document.
196
199
197
    finishedEvaluatingScript();
200
    String exceptionMessage;
201
    ScriptSourceCode sourceCode(m_startupData->sourceCode, URL(m_startupData->params.scriptURL));
202
    if (m_startupData->params.workerType == WorkerType::Classic) {
203
        scriptController->evaluate(sourceCode, &exceptionMessage);
204
        finishedEvaluatingScript();
205
    } else {
206
        // FIXME crossOrigin mode should be converted.
207
        // FIXME fix initiator name.
208
        // FIXME pass URL to module loader.
209
        dataLogLn("WORKER MODULE");
210
        auto moduleScript = LoadableModuleScript::create(emptyString(), emptyString(), m_startupData->params.referrerPolicy, ScriptElementCachedScriptFetcher::defaultCrossOriginModeForModule, emptyString(), emptyAtom(), false);
211
        MessageQueueWaitResult result = scriptController->loadModuleSynchronously(moduleScript.get(), sourceCode);
212
        dataLogLn("WORKER MODULE FETCHED");
213
        if (result != MessageQueueTerminated) {
214
            if (!moduleScript->error() && !moduleScript->wasCanceled()) {
215
                // Evaluate.
216
                scriptController->linkAndEvaluateModule(moduleScript.get(), sourceCode, &exceptionMessage);
217
                dataLogLn("WORKER MODULE EVALUATED");
218
                finishedEvaluatingScript();
219
            } else {
220
                // FIXME Throw an error.
221
            }
222
        }
223
    }
198
224
199
    callOnMainThread([evaluateCallback = WTFMove(m_evaluateCallback), message = exceptionMessage.isolatedCopy()] {
225
    callOnMainThread([evaluateCallback = WTFMove(m_evaluateCallback), message = exceptionMessage.isolatedCopy()] {
200
        if (evaluateCallback)
226
        if (evaluateCallback)
- a/Source/WebCore/workers/WorkerThread.h +4 lines
Lines 26-32 a/Source/WebCore/workers/WorkerThread.h_sec1
26
#pragma once
26
#pragma once
27
27
28
#include "ContentSecurityPolicyResponseHeaders.h"
28
#include "ContentSecurityPolicyResponseHeaders.h"
29
#include "FetchRequestCredentials.h"
29
#include "WorkerRunLoop.h"
30
#include "WorkerRunLoop.h"
31
#include "WorkerType.h"
30
#include <JavaScriptCore/RuntimeFlags.h>
32
#include <JavaScriptCore/RuntimeFlags.h>
31
#include <memory>
33
#include <memory>
32
#include <wtf/Forward.h>
34
#include <wtf/Forward.h>
Lines 68-73 struct WorkerParameters { a/Source/WebCore/workers/WorkerThread.h_sec2
68
    bool shouldBypassMainWorldContentSecurityPolicy;
70
    bool shouldBypassMainWorldContentSecurityPolicy;
69
    MonotonicTime timeOrigin;
71
    MonotonicTime timeOrigin;
70
    ReferrerPolicy referrerPolicy;
72
    ReferrerPolicy referrerPolicy;
73
    WorkerType workerType;
74
    FetchRequestCredentials credentials;
71
    bool requestAnimationFrameEnabled;
75
    bool requestAnimationFrameEnabled;
72
76
73
    WorkerParameters isolatedCopy() const;
77
    WorkerParameters isolatedCopy() const;
- a/Source/WebCore/workers/service/context/ServiceWorkerThread.cpp -2 / +2 lines
Lines 72-80 class DummyServiceWorkerThreadProxy : public WorkerObjectProxy { a/Source/WebCore/workers/service/context/ServiceWorkerThread.cpp_sec1
72
// FIXME: Use a valid WorkerReportingProxy
72
// FIXME: Use a valid WorkerReportingProxy
73
// FIXME: Use a valid WorkerObjectProxy
73
// FIXME: Use a valid WorkerObjectProxy
74
// FIXME: Use valid runtime flags
74
// FIXME: Use valid runtime flags
75
75
// FIXME: Use a valid WorkerType and Credentails for module service workers.
76
ServiceWorkerThread::ServiceWorkerThread(const ServiceWorkerContextData& data, String&& userAgent, WorkerLoaderProxy& loaderProxy, WorkerDebuggerProxy& debuggerProxy, IDBClient::IDBConnectionProxy* idbConnectionProxy, SocketProvider* socketProvider)
76
ServiceWorkerThread::ServiceWorkerThread(const ServiceWorkerContextData& data, String&& userAgent, WorkerLoaderProxy& loaderProxy, WorkerDebuggerProxy& debuggerProxy, IDBClient::IDBConnectionProxy* idbConnectionProxy, SocketProvider* socketProvider)
77
    : WorkerThread({ data.scriptURL, emptyString(), "serviceworker:" + Inspector::IdentifiersFactory::createIdentifier(), WTFMove(userAgent), platformStrategies()->loaderStrategy()->isOnLine(), data.contentSecurityPolicy, false, MonotonicTime::now(), { }, true }, data.script, loaderProxy, debuggerProxy, DummyServiceWorkerThreadProxy::shared(), WorkerThreadStartMode::Normal, data.registration.key.topOrigin().securityOrigin().get(), idbConnectionProxy, socketProvider, JSC::RuntimeFlags::createAllEnabled())
77
    : WorkerThread({ data.scriptURL, emptyString(), "serviceworker:" + Inspector::IdentifiersFactory::createIdentifier(), WTFMove(userAgent), platformStrategies()->loaderStrategy()->isOnLine(), data.contentSecurityPolicy, false, MonotonicTime::now(), { }, WorkerType::Classic, FetchRequestCredentials::SameOrigin, true }, data.script, loaderProxy, debuggerProxy, DummyServiceWorkerThreadProxy::shared(), WorkerThreadStartMode::Normal, data.registration.key.topOrigin().securityOrigin().get(), idbConnectionProxy, socketProvider, JSC::RuntimeFlags::createAllEnabled())
78
    , m_data(data.isolatedCopy())
78
    , m_data(data.isolatedCopy())
79
    , m_workerObjectProxy(DummyServiceWorkerThreadProxy::shared())
79
    , m_workerObjectProxy(DummyServiceWorkerThreadProxy::shared())
80
    , m_heartBeatTimeout(SWContextManager::singleton().connection()->shouldUseShortTimeout() ? heartBeatTimeoutForTest : heartBeatTimeout)
80
    , m_heartBeatTimeout(SWContextManager::singleton().connection()->shouldUseShortTimeout() ? heartBeatTimeoutForTest : heartBeatTimeout)

Return to Bug 164860