Title: [275443] trunk/Source
Revision
275443
Author
[email protected]
Date
2021-04-02 14:53:30 -0700 (Fri, 02 Apr 2021)

Log Message

Introduce ScriptBuffer class to wrap SharedBuffer containing a script
https://bugs.webkit.org/show_bug.cgi?id=224092

Reviewed by Yusuke Suzuki and Geoff Garen.

Introduce ScriptBuffer class to wrap SharedBuffer containing a script. We started using SharedBuffer to represent
worker scripts instead of String, so that they can hold file mapped data and be shared across processes.
This patch introduces a new ScriptBuffer to wrap those SharedBuffers. The type makes it clearer what type of
data we're dealing with. The helper functions used to convert between String and SharedBuffer can now simply
be member functions on ScriptBuffer. This also simplifies IPC code.

Source/WebCore:

* Sources.txt:
* WebCore.xcodeproj/project.pbxproj:
Add new ScriptBuffer class to project files.

* inspector/agents/worker/ServiceWorkerAgent.cpp:
(WebCore::ServiceWorkerAgent::getInitializationInfo):
Use ScriptBuffer::toString() instead of scriptBufferToString().

* workers/ScriptBuffer.cpp: Added.
(WebCore::ScriptBuffer::ScriptBuffer):
(WebCore::ScriptBuffer::toString const):
(WebCore::ScriptBuffer::containsSingleFileMappedSegment const):
(WebCore::operator==):
* workers/ScriptBuffer.h: Added.
(WebCore::ScriptBuffer::ScriptBuffer):
(WebCore::ScriptBuffer::buffer const):
(WebCore::ScriptBuffer::isolatedCopy const):
(WebCore::ScriptBuffer::operator bool const):
New ScriptBuffer class that wraps a SharedBuffer representation of a script.
This class helps make it clear what data we're dealing with. It also facilitates
conversion to and from a String when needed. The class also has its own IPC
coder at WebKit layer to encode the script as a ShareableResource when file
mapped.

* workers/WorkerScriptLoader.cpp:
(WebCore::WorkerScriptLoader::loadSynchronously):
Use ScriptBuffer::toString() instead of scriptBufferToString().
And use StringBuffer constructor that takes a String instead of stringToScriptBuffer().

* workers/service/SWClientConnection.h:
* workers/service/ServiceWorkerContextData.cpp:
(WebCore::ServiceWorkerContextData::isolatedCopy const):
* workers/service/ServiceWorkerContextData.h:
(WebCore::ServiceWorkerContextData::ImportedScript::encode const):
(WebCore::ServiceWorkerContextData::ImportedScript::decode):
(WebCore::ServiceWorkerContextData::ImportedScript::isolatedCopy const):
(WebCore::ServiceWorkerContextData::encode const):
(WebCore::ServiceWorkerContextData::decode):
- Use ScriptBuffer instead of RefPtr<SharedBuffer> for scripts.
- Drop scriptBufferToString() & stringToScriptBuffer() as they are no longer needed.
- Move IPC coders for ServiceWorkerContextData back from WebCoreArgumentCoders back
  to the WebCore class, now that the coders no longer need to deal with ShareableResource
  directly. We now encode / decode ScriptBuffer objects and its coder takes care of
  using a ShareableResource whenever possible.

* workers/service/ServiceWorkerGlobalScope.cpp:
(WebCore::ServiceWorkerGlobalScope::didSaveScriptsToDisk):
* workers/service/ServiceWorkerGlobalScope.h:
* workers/service/context/SWContextManager.cpp:
(WebCore::SWContextManager::didSaveScriptsToDisk):
* workers/service/context/SWContextManager.h:
* workers/service/context/ServiceWorkerThread.cpp:
(WebCore::ServiceWorkerThread::ServiceWorkerThread):
* workers/service/context/ServiceWorkerThreadProxy.cpp:
(WebCore::ServiceWorkerThreadProxy::didSaveScriptsToDisk):
* workers/service/context/ServiceWorkerThreadProxy.h:
* workers/service/server/RegistrationDatabase.cpp:
(WebCore::RegistrationDatabase::doPushChanges):
(WebCore::RegistrationDatabase::importRecords):
* workers/service/server/RegistrationStore.cpp:
(WebCore::RegistrationStore::didSaveWorkerScriptsToDisk):
* workers/service/server/RegistrationStore.h:
* workers/service/server/SWScriptStorage.cpp:
(WebCore::SWScriptStorage::store):
(WebCore::SWScriptStorage::retrieve):
* workers/service/server/SWScriptStorage.h:
* workers/service/server/SWServer.cpp:
(WebCore::SWServer::didSaveWorkerScriptsToDisk):
(WebCore::SWServer::updateWorker):
* workers/service/server/SWServer.h:
* workers/service/server/SWServerJobQueue.cpp:
(WebCore::SWServerJobQueue::scriptFetchFinished):
* workers/service/server/SWServerToContextConnection.h:
* workers/service/server/SWServerWorker.cpp:
(WebCore::SWServerWorker::SWServerWorker):
(WebCore::SWServerWorker::didSaveScriptsToDisk):
* workers/service/server/SWServerWorker.h:
(WebCore::SWServerWorker::script const):
Use ScriptBuffer instead of SharedBuffer.

Source/WebKit:

* NetworkProcess/ServiceWorker/WebSWServerToContextConnection.cpp:
(WebKit::WebSWServerToContextConnection::didSaveScriptsToDisk):
* NetworkProcess/ServiceWorker/WebSWServerToContextConnection.h:
Use ScriptBuffer instead SharedBuffer.

* Shared/WebCoreArgumentCoders.cpp:
(IPC::tryConvertToShareableResourceHandle):
(IPC::decodeScriptBufferAsShareableResourceHandle):
(IPC::ArgumentCoder<WebCore::ScriptBuffer>::encode):
(IPC::ArgumentCoder<WebCore::ScriptBuffer>::decode):
* Shared/WebCoreArgumentCoders.h:
- Add IPC encoder / decoder for ScriptBuffer which tries to encode / decode as a ShareableResource whenever
  possible (single segment that is file mapped). This logic used to be in the ServiceWorkerContextData
  coders. Now that the logic is in the ScriptBuffer coder, the ServiceWorkerContextData encoding / decoding
  becomes much simpler.
- Moved ServiceWorkerContextData coders from WebCoreArgumentCoders back to its class in WebCore, now that
  they no longer need to deal with ShareableResource directly.

* WebProcess/Storage/WebSWContextManagerConnection.cpp:
(WebKit::WebSWContextManagerConnection::didSaveScriptsToDisk):
* WebProcess/Storage/WebSWContextManagerConnection.h:
* WebProcess/Storage/WebSWContextManagerConnection.messages.in:
Send scripts over IPC as ScriptBuffer instead of using ShareableResource directly. The new IPC encoder /
decoder for ScriptBuffer takes care of using ShareableResource for us.

Modified Paths

Added Paths

Diff

Modified: trunk/Source/WebCore/ChangeLog (275442 => 275443)


--- trunk/Source/WebCore/ChangeLog	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/ChangeLog	2021-04-02 21:53:30 UTC (rev 275443)
@@ -1,5 +1,98 @@
 2021-04-02  Chris Dumez  <[email protected]>
 
+        Introduce ScriptBuffer class to wrap SharedBuffer containing a script
+        https://bugs.webkit.org/show_bug.cgi?id=224092
+
+        Reviewed by Yusuke Suzuki and Geoff Garen.
+
+        Introduce ScriptBuffer class to wrap SharedBuffer containing a script. We started using SharedBuffer to represent
+        worker scripts instead of String, so that they can hold file mapped data and be shared across processes.
+        This patch introduces a new ScriptBuffer to wrap those SharedBuffers. The type makes it clearer what type of
+        data we're dealing with. The helper functions used to convert between String and SharedBuffer can now simply
+        be member functions on ScriptBuffer. This also simplifies IPC code.
+
+        * Sources.txt:
+        * WebCore.xcodeproj/project.pbxproj:
+        Add new ScriptBuffer class to project files.
+
+        * inspector/agents/worker/ServiceWorkerAgent.cpp:
+        (WebCore::ServiceWorkerAgent::getInitializationInfo):
+        Use ScriptBuffer::toString() instead of scriptBufferToString().
+
+        * workers/ScriptBuffer.cpp: Added.
+        (WebCore::ScriptBuffer::ScriptBuffer):
+        (WebCore::ScriptBuffer::toString const):
+        (WebCore::ScriptBuffer::containsSingleFileMappedSegment const):
+        (WebCore::operator==):
+        * workers/ScriptBuffer.h: Added.
+        (WebCore::ScriptBuffer::ScriptBuffer):
+        (WebCore::ScriptBuffer::buffer const):
+        (WebCore::ScriptBuffer::isolatedCopy const):
+        (WebCore::ScriptBuffer::operator bool const):
+        New ScriptBuffer class that wraps a SharedBuffer representation of a script.
+        This class helps make it clear what data we're dealing with. It also facilitates
+        conversion to and from a String when needed. The class also has its own IPC
+        coder at WebKit layer to encode the script as a ShareableResource when file
+        mapped.
+
+        * workers/WorkerScriptLoader.cpp:
+        (WebCore::WorkerScriptLoader::loadSynchronously):
+        Use ScriptBuffer::toString() instead of scriptBufferToString().
+        And use StringBuffer constructor that takes a String instead of stringToScriptBuffer().
+
+        * workers/service/SWClientConnection.h:
+        * workers/service/ServiceWorkerContextData.cpp:
+        (WebCore::ServiceWorkerContextData::isolatedCopy const):
+        * workers/service/ServiceWorkerContextData.h:
+        (WebCore::ServiceWorkerContextData::ImportedScript::encode const):
+        (WebCore::ServiceWorkerContextData::ImportedScript::decode):
+        (WebCore::ServiceWorkerContextData::ImportedScript::isolatedCopy const):
+        (WebCore::ServiceWorkerContextData::encode const):
+        (WebCore::ServiceWorkerContextData::decode):
+        - Use ScriptBuffer instead of RefPtr<SharedBuffer> for scripts.
+        - Drop scriptBufferToString() & stringToScriptBuffer() as they are no longer needed.
+        - Move IPC coders for ServiceWorkerContextData back from WebCoreArgumentCoders back
+          to the WebCore class, now that the coders no longer need to deal with ShareableResource
+          directly. We now encode / decode ScriptBuffer objects and its coder takes care of
+          using a ShareableResource whenever possible.
+
+        * workers/service/ServiceWorkerGlobalScope.cpp:
+        (WebCore::ServiceWorkerGlobalScope::didSaveScriptsToDisk):
+        * workers/service/ServiceWorkerGlobalScope.h:
+        * workers/service/context/SWContextManager.cpp:
+        (WebCore::SWContextManager::didSaveScriptsToDisk):
+        * workers/service/context/SWContextManager.h:
+        * workers/service/context/ServiceWorkerThread.cpp:
+        (WebCore::ServiceWorkerThread::ServiceWorkerThread):
+        * workers/service/context/ServiceWorkerThreadProxy.cpp:
+        (WebCore::ServiceWorkerThreadProxy::didSaveScriptsToDisk):
+        * workers/service/context/ServiceWorkerThreadProxy.h:
+        * workers/service/server/RegistrationDatabase.cpp:
+        (WebCore::RegistrationDatabase::doPushChanges):
+        (WebCore::RegistrationDatabase::importRecords):
+        * workers/service/server/RegistrationStore.cpp:
+        (WebCore::RegistrationStore::didSaveWorkerScriptsToDisk):
+        * workers/service/server/RegistrationStore.h:
+        * workers/service/server/SWScriptStorage.cpp:
+        (WebCore::SWScriptStorage::store):
+        (WebCore::SWScriptStorage::retrieve):
+        * workers/service/server/SWScriptStorage.h:
+        * workers/service/server/SWServer.cpp:
+        (WebCore::SWServer::didSaveWorkerScriptsToDisk):
+        (WebCore::SWServer::updateWorker):
+        * workers/service/server/SWServer.h:
+        * workers/service/server/SWServerJobQueue.cpp:
+        (WebCore::SWServerJobQueue::scriptFetchFinished):
+        * workers/service/server/SWServerToContextConnection.h:
+        * workers/service/server/SWServerWorker.cpp:
+        (WebCore::SWServerWorker::SWServerWorker):
+        (WebCore::SWServerWorker::didSaveScriptsToDisk):
+        * workers/service/server/SWServerWorker.h:
+        (WebCore::SWServerWorker::script const):
+        Use ScriptBuffer instead of SharedBuffer.
+
+2021-04-02  Chris Dumez  <[email protected]>
+
         Unreviewed, reverting r275434.
 
         Need to figure out a better strategy to chose the color

Modified: trunk/Source/WebCore/Headers.cmake (275442 => 275443)


--- trunk/Source/WebCore/Headers.cmake	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/Headers.cmake	2021-04-02 21:53:30 UTC (rev 275443)
@@ -1645,6 +1645,7 @@
     testing/MockGamepad.h
     testing/MockGamepadProvider.h
 
+    workers/ScriptBuffer.h
     workers/WorkerAnimationController.h
     workers/WorkerDebuggerProxy.h
     workers/WorkerLoaderProxy.h

Modified: trunk/Source/WebCore/Sources.txt (275442 => 275443)


--- trunk/Source/WebCore/Sources.txt	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/Sources.txt	2021-04-02 21:53:30 UTC (rev 275443)
@@ -2642,6 +2642,7 @@
 workers/AbstractWorker.cpp
 workers/DedicatedWorkerGlobalScope.cpp
 workers/DedicatedWorkerThread.cpp
+workers/ScriptBuffer.cpp
 workers/Worker.cpp
 workers/WorkerAnimationController.cpp
 workers/WorkerConsoleClient.cpp

Modified: trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj (275442 => 275443)


--- trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj	2021-04-02 21:53:30 UTC (rev 275443)
@@ -1273,6 +1273,7 @@
 		460E3077222F4F03009A0606 /* DeviceOrientationOrMotionPermissionState.h in Headers */ = {isa = PBXBuildFile; fileRef = 465EDD9F222F4EC300B46E16 /* DeviceOrientationOrMotionPermissionState.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		46218ACB1F72D64E00574FBE /* DOMHighResTimeStamp.h in Headers */ = {isa = PBXBuildFile; fileRef = 46E016AD1F72D61E00282B2C /* DOMHighResTimeStamp.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		46273CAF260E59EF006FAA91 /* SWScriptStorage.h in Headers */ = {isa = PBXBuildFile; fileRef = 46273CAC260E59DF006FAA91 /* SWScriptStorage.h */; settings = {ATTRIBUTES = (Private, ); }; };
+		462E4C502616A811003A2C67 /* ScriptBuffer.h in Headers */ = {isa = PBXBuildFile; fileRef = 462E4C4D2616A801003A2C67 /* ScriptBuffer.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		463521AD2081092A00C28922 /* WindowProxy.h in Headers */ = {isa = PBXBuildFile; fileRef = 463521AA2081090B00C28922 /* WindowProxy.h */; settings = {ATTRIBUTES = (Private, ); }; };
 		463EB6231B8789E00096ED51 /* TagCollection.h in Headers */ = {isa = PBXBuildFile; fileRef = 463EB6211B8789CB0096ED51 /* TagCollection.h */; };
 		465307D01DB6EE4800E4137C /* JSUIEventInit.h in Headers */ = {isa = PBXBuildFile; fileRef = 83E045EF1DAA104F00B0D8B9 /* JSUIEventInit.h */; };
@@ -8251,6 +8252,8 @@
 		460D19441FCE21DD00C3DB85 /* JSServiceWorkerGlobalScopeCustom.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSServiceWorkerGlobalScopeCustom.cpp; sourceTree = "<group>"; };
 		46273CAC260E59DF006FAA91 /* SWScriptStorage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWScriptStorage.h; sourceTree = "<group>"; };
 		46273CAE260E59DF006FAA91 /* SWScriptStorage.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = SWScriptStorage.cpp; sourceTree = "<group>"; };
+		462E4C4D2616A801003A2C67 /* ScriptBuffer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ScriptBuffer.h; sourceTree = "<group>"; };
+		462E4C4F2616A801003A2C67 /* ScriptBuffer.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ScriptBuffer.cpp; sourceTree = "<group>"; };
 		4634592B1AC2271000ECB71C /* PowerObserverMac.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PowerObserverMac.cpp; sourceTree = "<group>"; };
 		463521AA2081090B00C28922 /* WindowProxy.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WindowProxy.h; sourceTree = "<group>"; };
 		463521AC2081090E00C28922 /* WindowProxy.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WindowProxy.cpp; sourceTree = "<group>"; };
@@ -19370,6 +19373,8 @@
 				4162A44F101145AE00DFF3ED /* DedicatedWorkerGlobalScope.idl */,
 				41A3D58C101C152D00316D07 /* DedicatedWorkerThread.cpp */,
 				41A3D58D101C152D00316D07 /* DedicatedWorkerThread.h */,
+				462E4C4F2616A801003A2C67 /* ScriptBuffer.cpp */,
+				462E4C4D2616A801003A2C67 /* ScriptBuffer.h */,
 				2E4346330F546A8200B0F1BA /* Worker.cpp */,
 				2E4346340F546A8200B0F1BA /* Worker.h */,
 				2E4346350F546A8200B0F1BA /* Worker.idl */,
@@ -34796,6 +34801,7 @@
 				BCEC01BE0C274DAC009F4EC9 /* Screen.h in Headers */,
 				C1E1D236203DF15400584665 /* ScreenProperties.h in Headers */,
 				A84D82C111D3474800972990 /* ScriptableDocumentParser.h in Headers */,
+				462E4C502616A811003A2C67 /* ScriptBuffer.h in Headers */,
 				41F1D21F0EF35C2A00DA8753 /* ScriptCachedFrameData.h in Headers */,
 				93B70D7009EB0C7C009D8468 /* ScriptController.h in Headers */,
 				E46B41F91CB24E70008F11DE /* ScriptDisallowedScope.h in Headers */,

Modified: trunk/Source/WebCore/inspector/agents/worker/ServiceWorkerAgent.cpp (275442 => 275443)


--- trunk/Source/WebCore/inspector/agents/worker/ServiceWorkerAgent.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/inspector/agents/worker/ServiceWorkerAgent.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -60,7 +60,7 @@
         .setTargetId(m_serviceWorkerGlobalScope.identifier())
         .setSecurityOrigin(m_serviceWorkerGlobalScope.securityOrigin()->toRawString())
         .setUrl(m_serviceWorkerGlobalScope.contextData().scriptURL.string())
-        .setContent(scriptBufferToString(m_serviceWorkerGlobalScope.contextData().script))
+        .setContent(m_serviceWorkerGlobalScope.contextData().script.toString())
         .release();
 }
 

Added: trunk/Source/WebCore/workers/ScriptBuffer.cpp (0 => 275443)


--- trunk/Source/WebCore/workers/ScriptBuffer.cpp	                        (rev 0)
+++ trunk/Source/WebCore/workers/ScriptBuffer.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2021 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "ScriptBuffer.h"
+
+#include <wtf/text/StringBuilder.h>
+
+namespace WebCore {
+
+ScriptBuffer::ScriptBuffer(const String& string)
+{
+    auto utf8 = string.utf8();
+    m_buffer = SharedBuffer::create(utf8.data(), utf8.length());
+}
+
+String ScriptBuffer::toString() const
+{
+    if (!m_buffer)
+        return String();
+
+    StringBuilder builder;
+    for (auto it = m_buffer->begin(); it != m_buffer->end(); ++it)
+        builder.append(String::fromUTF8(it->segment->data(), it->segment->size()));
+    return builder.toString();
+}
+
+bool ScriptBuffer::containsSingleFileMappedSegment() const
+{
+    return m_buffer && m_buffer->hasOneSegment() && m_buffer->begin()->segment->containsMappedFileData();
+}
+
+bool operator==(const ScriptBuffer& a, const ScriptBuffer& b)
+{
+    if (a.buffer() == b.buffer())
+        return true;
+    if (!a.buffer() || !b.buffer())
+        return false;
+    return *a.buffer() == *b.buffer();
+}
+
+} // namespace WebCore

Added: trunk/Source/WebCore/workers/ScriptBuffer.h (0 => 275443)


--- trunk/Source/WebCore/workers/ScriptBuffer.h	                        (rev 0)
+++ trunk/Source/WebCore/workers/ScriptBuffer.h	2021-04-02 21:53:30 UTC (rev 275443)
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2021 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include "SharedBuffer.h"
+
+namespace WebCore {
+
+class ScriptBuffer {
+public:
+    ScriptBuffer() = default;
+
+    ScriptBuffer(RefPtr<SharedBuffer>&& buffer)
+        : m_buffer(WTFMove(buffer))
+    {
+    }
+
+    explicit ScriptBuffer(const String&);
+
+    String toString() const;
+    SharedBuffer* buffer() const { return m_buffer.get(); }
+
+    ScriptBuffer isolatedCopy() const { return ScriptBuffer(m_buffer ? RefPtr<SharedBuffer>(m_buffer->copy()) : nullptr); }
+    explicit operator bool() const { return !!m_buffer; }
+
+    WEBCORE_EXPORT bool containsSingleFileMappedSegment() const;
+
+private:
+    RefPtr<SharedBuffer> m_buffer; // Contains the UTF-8 encoded script.
+};
+
+bool operator==(const ScriptBuffer&, const ScriptBuffer&);
+
+} // namespace WebCore

Modified: trunk/Source/WebCore/workers/WorkerScriptLoader.cpp (275442 => 275443)


--- trunk/Source/WebCore/workers/WorkerScriptLoader.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/WorkerScriptLoader.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -61,7 +61,7 @@
 
     if (isServiceWorkerGlobalScope) {
         if (auto* scriptResource = downcast<ServiceWorkerGlobalScope>(workerGlobalScope).scriptResource(url)) {
-            m_script.append(scriptBufferToString(*scriptResource->script));
+            m_script.append(scriptResource->script.toString());
             m_responseURL = scriptResource->responseURL;
             m_responseMIMEType = scriptResource->mimeType;
             return WTF::nullopt;
@@ -102,7 +102,7 @@
         if (!MIMETypeRegistry::isSupportedJavaScriptMIMEType(responseMIMEType()))
             return Exception { NetworkError, "mime type is not a supported _javascript_ mime type"_s };
 
-        downcast<ServiceWorkerGlobalScope>(workerGlobalScope).setScriptResource(url, ServiceWorkerContextData::ImportedScript { stringToScriptBuffer(script()), m_responseURL, m_responseMIMEType });
+        downcast<ServiceWorkerGlobalScope>(workerGlobalScope).setScriptResource(url, ServiceWorkerContextData::ImportedScript { ScriptBuffer { script() }, m_responseURL, m_responseMIMEType });
     }
 #endif
     return WTF::nullopt;

Modified: trunk/Source/WebCore/workers/service/SWClientConnection.h (275442 => 275443)


--- trunk/Source/WebCore/workers/service/SWClientConnection.h	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/SWClientConnection.h	2021-04-02 21:53:30 UTC (rev 275443)
@@ -42,7 +42,6 @@
 class SerializedScriptValue;
 class ServiceWorkerContainer;
 class ServiceWorkerRegistration;
-class SharedBuffer;
 enum class ServiceWorkerRegistrationState : uint8_t;
 enum class ServiceWorkerState : uint8_t;
 enum class ShouldNotifyWhenResolved : bool;

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerContextData.cpp (275442 => 275443)


--- trunk/Source/WebCore/workers/service/ServiceWorkerContextData.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerContextData.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -37,7 +37,7 @@
         jobDataIdentifier,
         registration.isolatedCopy(),
         serviceWorkerIdentifier,
-        script->copy(),
+        script.isolatedCopy(),
         certificateInfo.isolatedCopy(),
         contentSecurityPolicy.isolatedCopy(),
         referrerPolicy.isolatedCopy(),
@@ -48,20 +48,6 @@
     };
 }
 
-String scriptBufferToString(SharedBuffer& buffer)
-{
-    StringBuilder builder;
-    for (auto it = buffer.begin(); it != buffer.end(); ++it)
-        builder.append(String::fromUTF8(it->segment->data(), it->segment->size()));
-    return builder.toString();
-}
-
-Ref<SharedBuffer> stringToScriptBuffer(const String& string)
-{
-    auto utf8 = string.utf8();
-    return SharedBuffer::create(utf8.data(), utf8.length());
-}
-
 } // namespace WebCore
 
 #endif // ENABLE(SERVICE_WORKER)

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerContextData.h (275442 => 275443)


--- trunk/Source/WebCore/workers/service/ServiceWorkerContextData.h	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerContextData.h	2021-04-02 21:53:30 UTC (rev 275443)
@@ -27,10 +27,10 @@
 
 #include "CertificateInfo.h"
 #include "ContentSecurityPolicyResponseHeaders.h"
+#include "ScriptBuffer.h"
 #include "ServiceWorkerIdentifier.h"
 #include "ServiceWorkerJobDataIdentifier.h"
 #include "ServiceWorkerRegistrationData.h"
-#include "SharedBuffer.h"
 #include "WorkerType.h"
 #include <wtf/HashMap.h>
 #include <wtf/URL.h>
@@ -40,22 +40,48 @@
 
 namespace WebCore {
 
-String scriptBufferToString(SharedBuffer&);
-Ref<SharedBuffer> stringToScriptBuffer(const String&);
-
 struct ServiceWorkerContextData {
     struct ImportedScript {
-        RefPtr<SharedBuffer> script;
+        ScriptBuffer script;
         URL responseURL;
         String mimeType;
 
-        ImportedScript isolatedCopy() const { return { script->copy(), responseURL.isolatedCopy(), mimeType.isolatedCopy() }; }
+        template<class Encoder> void encode(Encoder& encoder) const
+        {
+            encoder << script << responseURL << mimeType;
+        }
+
+        template<class Decoder> static Optional<ImportedScript> decode(Decoder& decoder)
+        {
+            Optional<ScriptBuffer> script;
+            decoder >> script;
+            if (!script)
+                return WTF::nullopt;
+
+            Optional<URL> responseURL;
+            decoder >> responseURL;
+            if (!responseURL)
+                return WTF::nullopt;
+
+            Optional<String> mimeType;
+            decoder >> mimeType;
+            if (!mimeType)
+                return WTF::nullopt;
+
+            return {{
+                WTFMove(*script),
+                WTFMove(*responseURL),
+                WTFMove(*mimeType)
+            }};
+        }
+
+        ImportedScript isolatedCopy() const { return { script.isolatedCopy(), responseURL.isolatedCopy(), mimeType.isolatedCopy() }; }
     };
 
     Optional<ServiceWorkerJobDataIdentifier> jobDataIdentifier;
     ServiceWorkerRegistrationData registration;
     ServiceWorkerIdentifier serviceWorkerIdentifier;
-    Ref<SharedBuffer> script;
+    ScriptBuffer script;
     CertificateInfo certificateInfo;
     ContentSecurityPolicyResponseHeaders contentSecurityPolicy;
     String referrerPolicy;
@@ -64,9 +90,85 @@
     bool loadedFromDisk;
     HashMap<URL, ImportedScript> scriptResourceMap;
 
+    template<class Encoder> void encode(Encoder&) const;
+    template<class Decoder> static Optional<ServiceWorkerContextData> decode(Decoder&);
+
     ServiceWorkerContextData isolatedCopy() const;
 };
 
+template<class Encoder>
+void ServiceWorkerContextData::encode(Encoder& encoder) const
+{
+    encoder << jobDataIdentifier << registration << serviceWorkerIdentifier << script << contentSecurityPolicy << referrerPolicy
+        << scriptURL << workerType << loadedFromDisk << scriptResourceMap << certificateInfo;
+}
+
+template<class Decoder>
+Optional<ServiceWorkerContextData> ServiceWorkerContextData::decode(Decoder& decoder)
+{
+    Optional<Optional<ServiceWorkerJobDataIdentifier>> jobDataIdentifier;
+    decoder >> jobDataIdentifier;
+    if (!jobDataIdentifier)
+        return WTF::nullopt;
+
+    Optional<ServiceWorkerRegistrationData> registration;
+    decoder >> registration;
+    if (!registration)
+        return WTF::nullopt;
+
+    auto serviceWorkerIdentifier = ServiceWorkerIdentifier::decode(decoder);
+    if (!serviceWorkerIdentifier)
+        return WTF::nullopt;
+
+    Optional<ScriptBuffer> script;
+    decoder >> script;
+    if (!script)
+        return WTF::nullopt;
+
+    ContentSecurityPolicyResponseHeaders contentSecurityPolicy;
+    if (!decoder.decode(contentSecurityPolicy))
+        return WTF::nullopt;
+
+    String referrerPolicy;
+    if (!decoder.decode(referrerPolicy))
+        return WTF::nullopt;
+
+    URL scriptURL;
+    if (!decoder.decode(scriptURL))
+        return WTF::nullopt;
+
+    WorkerType workerType;
+    if (!decoder.decode(workerType))
+        return WTF::nullopt;
+
+    bool loadedFromDisk;
+    if (!decoder.decode(loadedFromDisk))
+        return WTF::nullopt;
+
+    HashMap<URL, ImportedScript> scriptResourceMap;
+    if (!decoder.decode(scriptResourceMap))
+        return WTF::nullopt;
+
+    Optional<CertificateInfo> certificateInfo;
+    decoder >> certificateInfo;
+    if (!certificateInfo)
+        return WTF::nullopt;
+
+    return {{
+        WTFMove(*jobDataIdentifier),
+        WTFMove(*registration),
+        WTFMove(*serviceWorkerIdentifier),
+        WTFMove(*script),
+        WTFMove(*certificateInfo),
+        WTFMove(contentSecurityPolicy),
+        WTFMove(referrerPolicy),
+        WTFMove(scriptURL),
+        workerType,
+        loadedFromDisk,
+        WTFMove(scriptResourceMap)
+    }};
+}
+
 } // namespace WebCore
 
 #endif // ENABLE(SERVICE_WORKER)

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerGlobalScope.cpp (275442 => 275443)


--- trunk/Source/WebCore/workers/service/ServiceWorkerGlobalScope.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerGlobalScope.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -155,18 +155,18 @@
     m_contextData.scriptResourceMap.set(url, WTFMove(script));
 }
 
-void ServiceWorkerGlobalScope::didSaveScriptsToDisk(RefPtr<SharedBuffer>&& script, HashMap<URL, RefPtr<SharedBuffer>>&& importedScripts)
+void ServiceWorkerGlobalScope::didSaveScriptsToDisk(ScriptBuffer&& script, HashMap<URL, ScriptBuffer>&& importedScripts)
 {
     // These scripts should be identical to the ones we have. However, these are mmap'd so using them helps reduce dirty memory usage.
     if (script) {
-        ASSERT(m_contextData.script.get() == *script);
-        m_contextData.script = script.releaseNonNull();
+        ASSERT(m_contextData.script == script);
+        m_contextData.script = WTFMove(script);
     }
     for (auto& pair : importedScripts) {
         auto it = m_contextData.scriptResourceMap.find(pair.key);
         if (it == m_contextData.scriptResourceMap.end())
             continue;
-        ASSERT(*it->value.script == *pair.value); // Do a memcmp to make sure the scripts are identical.
+        ASSERT(it->value.script == pair.value); // Do a memcmp to make sure the scripts are identical.
         it->value.script = WTFMove(pair.value);
     }
 }

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerGlobalScope.h (275442 => 275443)


--- trunk/Source/WebCore/workers/service/ServiceWorkerGlobalScope.h	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerGlobalScope.h	2021-04-02 21:53:30 UTC (rev 275443)
@@ -68,7 +68,7 @@
     const ServiceWorkerContextData::ImportedScript* scriptResource(const URL&) const;
     void setScriptResource(const URL&, ServiceWorkerContextData::ImportedScript&&);
 
-    void didSaveScriptsToDisk(RefPtr<SharedBuffer>&& script, HashMap<URL, RefPtr<SharedBuffer>>&& importedScripts);
+    void didSaveScriptsToDisk(ScriptBuffer&&, HashMap<URL, ScriptBuffer>&& importedScripts);
 
     const ServiceWorkerContextData& contextData() const { return m_contextData; }
     const CertificateInfo& certificateInfo() const { return m_contextData.certificateInfo; }

Modified: trunk/Source/WebCore/workers/service/context/SWContextManager.cpp (275442 => 275443)


--- trunk/Source/WebCore/workers/service/context/SWContextManager.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/context/SWContextManager.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -120,7 +120,7 @@
     stopWorker(*serviceWorker, timeout, WTFMove(completionHandler));
 }
 
-void SWContextManager::didSaveScriptsToDisk(ServiceWorkerIdentifier identifier, RefPtr<SharedBuffer>&& script, HashMap<URL, RefPtr<SharedBuffer>>&& importedScripts)
+void SWContextManager::didSaveScriptsToDisk(ServiceWorkerIdentifier identifier, ScriptBuffer&& script, HashMap<URL, ScriptBuffer>&& importedScripts)
 {
     if (auto serviceWorker = m_workerMap.get(identifier))
         serviceWorker->didSaveScriptsToDisk(WTFMove(script), WTFMove(importedScripts));

Modified: trunk/Source/WebCore/workers/service/context/SWContextManager.h (275442 => 275443)


--- trunk/Source/WebCore/workers/service/context/SWContextManager.h	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/context/SWContextManager.h	2021-04-02 21:53:30 UTC (rev 275443)
@@ -90,7 +90,7 @@
     WEBCORE_EXPORT void fireInstallEvent(ServiceWorkerIdentifier);
     WEBCORE_EXPORT void fireActivateEvent(ServiceWorkerIdentifier);
     WEBCORE_EXPORT void terminateWorker(ServiceWorkerIdentifier, Seconds timeout, Function<void()>&&);
-    WEBCORE_EXPORT void didSaveScriptsToDisk(ServiceWorkerIdentifier, RefPtr<SharedBuffer>&& script, HashMap<URL, RefPtr<SharedBuffer>>&& importedScripts);
+    WEBCORE_EXPORT void didSaveScriptsToDisk(ServiceWorkerIdentifier, ScriptBuffer&&, HashMap<URL, ScriptBuffer>&& importedScripts);
 
     void forEachServiceWorkerThread(const WTF::Function<void(ServiceWorkerThreadProxy&)>&);
 

Modified: trunk/Source/WebCore/workers/service/context/ServiceWorkerThread.cpp (275442 => 275443)


--- trunk/Source/WebCore/workers/service/context/ServiceWorkerThread.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/context/ServiceWorkerThread.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -74,7 +74,7 @@
 // FIXME: Use valid runtime flags
 
 ServiceWorkerThread::ServiceWorkerThread(ServiceWorkerContextData&& data, String&& userAgent, const Settings::Values& settingsValues, WorkerLoaderProxy& loaderProxy, WorkerDebuggerProxy& debuggerProxy, IDBClient::IDBConnectionProxy* idbConnectionProxy, SocketProvider* socketProvider)
-    : WorkerThread({ data.scriptURL, emptyString(), "serviceworker:" + Inspector::IdentifiersFactory::createIdentifier(), WTFMove(userAgent), platformStrategies()->loaderStrategy()->isOnLine(), data.contentSecurityPolicy, false, MonotonicTime::now(), { }, data.workerType, FetchRequestCredentials::Omit, settingsValues }, scriptBufferToString(data.script), loaderProxy, debuggerProxy, DummyServiceWorkerThreadProxy::shared(), WorkerThreadStartMode::Normal, data.registration.key.topOrigin().securityOrigin().get(), idbConnectionProxy, socketProvider, JSC::RuntimeFlags::createAllEnabled())
+    : WorkerThread({ data.scriptURL, emptyString(), "serviceworker:" + Inspector::IdentifiersFactory::createIdentifier(), WTFMove(userAgent), platformStrategies()->loaderStrategy()->isOnLine(), data.contentSecurityPolicy, false, MonotonicTime::now(), { }, data.workerType, FetchRequestCredentials::Omit, settingsValues }, data.script.toString(), loaderProxy, debuggerProxy, DummyServiceWorkerThreadProxy::shared(), WorkerThreadStartMode::Normal, data.registration.key.topOrigin().securityOrigin().get(), idbConnectionProxy, socketProvider, JSC::RuntimeFlags::createAllEnabled())
     , m_serviceWorkerIdentifier(data.serviceWorkerIdentifier)
     , m_jobDataIdentifier(data.jobDataIdentifier)
     , m_data(crossThreadCopy(data))

Modified: trunk/Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.cpp (275442 => 275443)


--- trunk/Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -281,7 +281,7 @@
     });
 }
 
-void ServiceWorkerThreadProxy::didSaveScriptsToDisk(RefPtr<SharedBuffer>&& script, HashMap<URL, RefPtr<SharedBuffer>>&& importedScripts)
+void ServiceWorkerThreadProxy::didSaveScriptsToDisk(ScriptBuffer&& script, HashMap<URL, ScriptBuffer>&& importedScripts)
 {
     thread().runLoop().postTask([script = WTFMove(script), importedScripts = WTFMove(importedScripts)](auto& context) mutable {
         downcast<ServiceWorkerGlobalScope>(context).didSaveScriptsToDisk(WTFMove(script), WTFMove(importedScripts));

Modified: trunk/Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.h (275442 => 275443)


--- trunk/Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.h	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/context/ServiceWorkerThreadProxy.h	2021-04-02 21:53:30 UTC (rev 275443)
@@ -78,7 +78,7 @@
     void postMessageToServiceWorker(MessageWithMessagePorts&&, ServiceWorkerOrClientData&&);
     void fireInstallEvent();
     void fireActivateEvent();
-    void didSaveScriptsToDisk(RefPtr<SharedBuffer>&& script, HashMap<URL, RefPtr<SharedBuffer>>&& importedScripts);
+    void didSaveScriptsToDisk(ScriptBuffer&&, HashMap<URL, ScriptBuffer>&& importedScripts);
 
     WEBCORE_EXPORT void setLastNavigationWasAppBound(bool);
 

Modified: trunk/Source/WebCore/workers/service/server/RegistrationDatabase.cpp (275442 => 275443)


--- trunk/Source/WebCore/workers/service/server/RegistrationDatabase.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/server/RegistrationDatabase.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -469,14 +469,14 @@
         ASSERT(mainScript);
         if (!mainScript)
             return false;
-        HashMap<URL, RefPtr<SharedBuffer>> importedScripts;
+        HashMap<URL, ScriptBuffer> importedScripts;
         for (auto& pair : data.scriptResourceMap) {
-            auto importedScript = scriptStorage.store(data.registration.key, pair.key, *pair.value.script);
+            auto importedScript = scriptStorage.store(data.registration.key, pair.key, pair.value.script);
             ASSERT(importedScript);
             if (importedScript)
-                importedScripts.add(crossThreadCopy(pair.key), WTFMove(importedScript));
+                importedScripts.add(crossThreadCopy(pair.key), crossThreadCopy(importedScript));
         }
-        callOnMainThread([this, protectedThis = makeRef(*this), serviceWorkerIdentifier = data.serviceWorkerIdentifier, mainScript = mainScript.releaseNonNull(), importedScripts = WTFMove(importedScripts)]() mutable {
+        callOnMainThread([this, protectedThis = makeRef(*this), serviceWorkerIdentifier = data.serviceWorkerIdentifier, mainScript = crossThreadCopy(mainScript), importedScripts = WTFMove(importedScripts)]() mutable {
             if (m_store)
                 m_store->didSaveWorkerScriptsToDisk(serviceWorkerIdentifier, WTFMove(mainScript), WTFMove(importedScripts));
         });
@@ -569,7 +569,7 @@
         auto registrationIdentifier = ServiceWorkerRegistrationIdentifier::generate();
         auto serviceWorkerData = ServiceWorkerData { workerIdentifier, scriptURL, ServiceWorkerState::Activated, *workerType, registrationIdentifier };
         auto registration = ServiceWorkerRegistrationData { WTFMove(*key), registrationIdentifier, WTFMove(scopeURL), *updateViaCache, lastUpdateCheckTime, WTF::nullopt, WTF::nullopt, WTFMove(serviceWorkerData) };
-        auto contextData = ServiceWorkerContextData { WTF::nullopt, WTFMove(registration), workerIdentifier, script.releaseNonNull(), WTFMove(*certificateInfo), WTFMove(*contentSecurityPolicy), WTFMove(referrerPolicy), WTFMove(scriptURL), *workerType, true, WTFMove(scriptResourceMap) };
+        auto contextData = ServiceWorkerContextData { WTF::nullopt, WTFMove(registration), workerIdentifier, WTFMove(script), WTFMove(*certificateInfo), WTFMove(*contentSecurityPolicy), WTFMove(referrerPolicy), WTFMove(scriptURL), *workerType, true, WTFMove(scriptResourceMap) };
 
         callOnMainThread([protectedThis = makeRef(*this), contextData = contextData.isolatedCopy()]() mutable {
             protectedThis->addRegistrationToStore(WTFMove(contextData));

Modified: trunk/Source/WebCore/workers/service/server/RegistrationStore.cpp (275442 => 275443)


--- trunk/Source/WebCore/workers/service/server/RegistrationStore.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/server/RegistrationStore.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -128,7 +128,7 @@
     m_server.addRegistrationFromStore(WTFMove(data));
 }
 
-void RegistrationStore::didSaveWorkerScriptsToDisk(ServiceWorkerIdentifier serviceWorkerIdentifier, Ref<SharedBuffer>&& mainScript, HashMap<URL, RefPtr<SharedBuffer>>&& importedScripts)
+void RegistrationStore::didSaveWorkerScriptsToDisk(ServiceWorkerIdentifier serviceWorkerIdentifier, ScriptBuffer&& mainScript, HashMap<URL, ScriptBuffer>&& importedScripts)
 {
     m_server.didSaveWorkerScriptsToDisk(serviceWorkerIdentifier, WTFMove(mainScript), WTFMove(importedScripts));
 }

Modified: trunk/Source/WebCore/workers/service/server/RegistrationStore.h (275442 => 275443)


--- trunk/Source/WebCore/workers/service/server/RegistrationStore.h	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/server/RegistrationStore.h	2021-04-02 21:53:30 UTC (rev 275443)
@@ -63,7 +63,7 @@
     void addRegistrationFromDatabase(ServiceWorkerContextData&&);
     void databaseFailedToOpen();
     void databaseOpenedAndRecordsImported();
-    void didSaveWorkerScriptsToDisk(ServiceWorkerIdentifier, Ref<SharedBuffer>&& mainScript, HashMap<URL, RefPtr<SharedBuffer>>&& importedScripts);
+    void didSaveWorkerScriptsToDisk(ServiceWorkerIdentifier, ScriptBuffer&& mainScript, HashMap<URL, ScriptBuffer>&& importedScripts);
 
     SWServer& server() { return m_server; };
 

Modified: trunk/Source/WebCore/workers/service/server/SWScriptStorage.cpp (275442 => 275443)


--- trunk/Source/WebCore/workers/service/server/SWScriptStorage.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/server/SWScriptStorage.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -28,8 +28,8 @@
 
 #if ENABLE(SERVICE_WORKER)
 #include "Logging.h"
+#include "ScriptBuffer.h"
 #include "ServiceWorkerRegistrationKey.h"
-#include "SharedBuffer.h"
 #include <pal/crypto/CryptoDigest.h>
 #include <wtf/MainThread.h>
 #include <wtf/PageBlock.h>
@@ -79,7 +79,7 @@
     return FileSystem::pathByAppendingComponent(registrationDirectory(registrationKey), sha2Hash(scriptURL));
 }
 
-RefPtr<SharedBuffer> SWScriptStorage::store(const ServiceWorkerRegistrationKey& registrationKey, const URL& scriptURL, const SharedBuffer& script)
+ScriptBuffer SWScriptStorage::store(const ServiceWorkerRegistrationKey& registrationKey, const URL& scriptURL, const ScriptBuffer& script)
 {
     ASSERT(!isMainThread());
 
@@ -87,15 +87,15 @@
     FileSystem::makeAllDirectories(FileSystem::directoryName(scriptPath));
 
     auto iterateOverBufferAndWriteData = [&](const Function<bool(const uint8_t*, size_t)>& writeData) {
-        for (auto it = script.begin(); it != script.end(); ++it)
+        for (auto it = script.buffer()->begin(); it != script.buffer()->end(); ++it)
             writeData(reinterpret_cast<const uint8_t*>(it->segment->data()), it->segment->size());
     };
 
-    if (!shouldUseFileMapping(script.size())) {
+    if (!shouldUseFileMapping(script.buffer()->size())) {
         auto handle = FileSystem::openFile(scriptPath, FileSystem::FileOpenMode::Write);
         if (!FileSystem::isHandleValid(handle)) {
             RELEASE_LOG_ERROR(ServiceWorker, "SWScriptStorage::store: Failure to store %s, FileSystem::openFile() failed", scriptPath.utf8().data());
-            return nullptr;
+            return { };
         }
         iterateOverBufferAndWriteData([&](const uint8_t* data, size_t size) {
             FileSystem::writeToFile(handle, reinterpret_cast<const char*>(data), size);
@@ -102,20 +102,20 @@
             return true;
         });
         FileSystem::closeFile(handle);
-        return script.copy();
+        return script;
     }
 
     // Make sure we delete the file before writing as there may be code using a mmap'd version of this file.
     FileSystem::deleteFile(scriptPath);
-    auto mappedFile = FileSystem::mapToFile(scriptPath, script.size(), WTFMove(iterateOverBufferAndWriteData));
+    auto mappedFile = FileSystem::mapToFile(scriptPath, script.buffer()->size(), WTFMove(iterateOverBufferAndWriteData));
     if (!mappedFile) {
         RELEASE_LOG_ERROR(ServiceWorker, "SWScriptStorage::store: Failure to store %s, FileSystem::mapToFile() failed", scriptPath.utf8().data());
-        return nullptr;
+        return { };
     }
-    return SharedBuffer::create(WTFMove(mappedFile));
+    return ScriptBuffer { SharedBuffer::create(WTFMove(mappedFile)) };
 }
 
-RefPtr<SharedBuffer> SWScriptStorage::retrieve(const ServiceWorkerRegistrationKey& registrationKey, const URL& scriptURL)
+ScriptBuffer SWScriptStorage::retrieve(const ServiceWorkerRegistrationKey& registrationKey, const URL& scriptURL)
 {
     ASSERT(!isMainThread());
 
@@ -123,7 +123,7 @@
     long long fileSize = 0;
     if (!FileSystem::getFileSize(scriptPath, fileSize)) {
         RELEASE_LOG_ERROR(ServiceWorker, "SWScriptStorage::retrieve: Failure to retrieve %s, FileSystem::getFileSize() failed", scriptPath.utf8().data());
-        return nullptr;
+        return { };
     }
 
     // FIXME: Do we need to disable file mapping in more cases to avoid having too many file descriptors open?

Modified: trunk/Source/WebCore/workers/service/server/SWScriptStorage.h (275442 => 275443)


--- trunk/Source/WebCore/workers/service/server/SWScriptStorage.h	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/server/SWScriptStorage.h	2021-04-02 21:53:30 UTC (rev 275443)
@@ -33,7 +33,7 @@
 namespace WebCore {
 
 class ServiceWorkerRegistrationKey;
-class SharedBuffer;
+class ScriptBuffer;
 
 class SWScriptStorage {
     WTF_MAKE_FAST_ALLOCATED;
@@ -40,8 +40,8 @@
 public:
     explicit SWScriptStorage(const String& directory);
 
-    RefPtr<SharedBuffer> store(const ServiceWorkerRegistrationKey&, const URL& scriptURL, const SharedBuffer& script);
-    RefPtr<SharedBuffer> retrieve(const ServiceWorkerRegistrationKey&, const URL& scriptURL);
+    ScriptBuffer store(const ServiceWorkerRegistrationKey&, const URL& scriptURL, const ScriptBuffer&);
+    ScriptBuffer retrieve(const ServiceWorkerRegistrationKey&, const URL& scriptURL);
     void clear(const ServiceWorkerRegistrationKey&);
 
 private:

Modified: trunk/Source/WebCore/workers/service/server/SWServer.cpp (275442 => 275443)


--- trunk/Source/WebCore/workers/service/server/SWServer.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/server/SWServer.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -176,7 +176,7 @@
     });
 }
 
-void SWServer::didSaveWorkerScriptsToDisk(ServiceWorkerIdentifier serviceWorkerIdentifier, Ref<SharedBuffer>&& mainScript, HashMap<URL, RefPtr<SharedBuffer>>&& importedScripts)
+void SWServer::didSaveWorkerScriptsToDisk(ServiceWorkerIdentifier serviceWorkerIdentifier, ScriptBuffer&& mainScript, HashMap<URL, ScriptBuffer>&& importedScripts)
 {
     if (auto worker = workerByID(serviceWorkerIdentifier))
         worker->didSaveScriptsToDisk(WTFMove(mainScript), WTFMove(importedScripts));
@@ -639,7 +639,7 @@
 
 void SWServer::updateWorker(const ServiceWorkerJobDataIdentifier& jobDataIdentifier, SWServerRegistration& registration, const URL& url, const String& script, const CertificateInfo& certificateInfo, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicy, const String& referrerPolicy, WorkerType type, HashMap<URL, ServiceWorkerContextData::ImportedScript>&& scriptResourceMap)
 {
-    tryInstallContextData(ServiceWorkerContextData { jobDataIdentifier, registration.data(), ServiceWorkerIdentifier::generate(), stringToScriptBuffer(script), certificateInfo, contentSecurityPolicy, referrerPolicy, url, type, false, WTFMove(scriptResourceMap) });
+    tryInstallContextData(ServiceWorkerContextData { jobDataIdentifier, registration.data(), ServiceWorkerIdentifier::generate(), ScriptBuffer { script }, certificateInfo, contentSecurityPolicy, referrerPolicy, url, type, false, WTFMove(scriptResourceMap) });
 }
 
 void SWServer::tryInstallContextData(ServiceWorkerContextData&& data)

Modified: trunk/Source/WebCore/workers/service/server/SWServer.h (275442 => 275443)


--- trunk/Source/WebCore/workers/service/server/SWServer.h	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/server/SWServer.h	2021-04-02 21:53:30 UTC (rev 275443)
@@ -190,7 +190,7 @@
     void resolveRegistrationReadyRequests(SWServerRegistration&);
 
     void addRegistrationFromStore(ServiceWorkerContextData&&);
-    void didSaveWorkerScriptsToDisk(ServiceWorkerIdentifier, Ref<SharedBuffer>&& mainScript, HashMap<URL, RefPtr<SharedBuffer>>&& importedScripts);
+    void didSaveWorkerScriptsToDisk(ServiceWorkerIdentifier, ScriptBuffer&& mainScript, HashMap<URL, ScriptBuffer>&& importedScripts);
     void registrationStoreImportComplete();
     void registrationStoreDatabaseFailedToOpen();
 

Modified: trunk/Source/WebCore/workers/service/server/SWServerJobQueue.cpp (275442 => 275443)


--- trunk/Source/WebCore/workers/service/server/SWServerJobQueue.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/server/SWServerJobQueue.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -100,7 +100,7 @@
     // If newestWorker is not null, newestWorker's script url equals job's script url with the exclude fragments
     // flag set, and script's source text is a byte-for-byte match with newestWorker's script resource's source
     // text, then:
-    if (newestWorker && equalIgnoringFragmentIdentifier(newestWorker->scriptURL(), job.scriptURL) && newestWorker->type() == job.workerType && result.script == scriptBufferToString(newestWorker->script()) && doCertificatesMatch(result.certificateInfo, newestWorker->certificateInfo())) {
+    if (newestWorker && equalIgnoringFragmentIdentifier(newestWorker->scriptURL(), job.scriptURL) && newestWorker->type() == job.workerType && result.script == newestWorker->script().toString() && doCertificatesMatch(result.certificateInfo, newestWorker->certificateInfo())) {
         RELEASE_LOG(ServiceWorker, "%p - SWServerJobQueue::scriptFetchFinished, script and certificate are matching for registrationID=%llu", this, registration->identifier().toUInt64());
         // FIXME: for non classic scripts, check the script’s module record's [[ECMAScriptCode]].
 

Modified: trunk/Source/WebCore/workers/service/server/SWServerToContextConnection.h (275442 => 275443)


--- trunk/Source/WebCore/workers/service/server/SWServerToContextConnection.h	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/server/SWServerToContextConnection.h	2021-04-02 21:53:30 UTC (rev 275443)
@@ -54,7 +54,7 @@
     virtual void fireInstallEvent(ServiceWorkerIdentifier) = 0;
     virtual void fireActivateEvent(ServiceWorkerIdentifier) = 0;
     virtual void terminateWorker(ServiceWorkerIdentifier) = 0;
-    virtual void didSaveScriptsToDisk(ServiceWorkerIdentifier, SharedBuffer& script, const HashMap<URL, RefPtr<SharedBuffer>>& importedScripts) = 0;
+    virtual void didSaveScriptsToDisk(ServiceWorkerIdentifier, const ScriptBuffer&, const HashMap<URL, ScriptBuffer>& importedScripts) = 0;
     virtual void findClientByIdentifierCompleted(uint64_t requestIdentifier, const Optional<ServiceWorkerClientData>&, bool hasSecurityError) = 0;
     virtual void matchAllCompleted(uint64_t requestIdentifier, const Vector<ServiceWorkerClientData>&) = 0;
 

Modified: trunk/Source/WebCore/workers/service/server/SWServerWorker.cpp (275442 => 275443)


--- trunk/Source/WebCore/workers/service/server/SWServerWorker.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/server/SWServerWorker.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -49,7 +49,7 @@
 }
 
 // FIXME: Use r-value references for script and contentSecurityPolicy
-SWServerWorker::SWServerWorker(SWServer& server, SWServerRegistration& registration, const URL& scriptURL, SharedBuffer& script, const CertificateInfo& certificateInfo, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicy, String&& referrerPolicy, WorkerType type, ServiceWorkerIdentifier identifier, HashMap<URL, ServiceWorkerContextData::ImportedScript>&& scriptResourceMap)
+SWServerWorker::SWServerWorker(SWServer& server, SWServerRegistration& registration, const URL& scriptURL, const ScriptBuffer& script, const CertificateInfo& certificateInfo, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicy, String&& referrerPolicy, WorkerType type, ServiceWorkerIdentifier identifier, HashMap<URL, ServiceWorkerContextData::ImportedScript>&& scriptResourceMap)
     : m_server(makeWeakPtr(server))
     , m_registrationKey(registration.key())
     , m_registration(makeWeakPtr(registration))
@@ -238,7 +238,7 @@
     m_scriptResourceMap.set(WTFMove(url), WTFMove(script));
 }
 
-void SWServerWorker::didSaveScriptsToDisk(Ref<SharedBuffer>&& mainScript, HashMap<URL, RefPtr<SharedBuffer>>&& importedScripts)
+void SWServerWorker::didSaveScriptsToDisk(ScriptBuffer&& mainScript, HashMap<URL, ScriptBuffer>&& importedScripts)
 {
     // Send mmap'd version of the scripts to the ServiceWorker process so we can save dirty memory.
     if (auto* contextConnection = this->contextConnection())
@@ -245,7 +245,7 @@
         contextConnection->didSaveScriptsToDisk(identifier(), mainScript, importedScripts);
 
     // The scripts were saved to disk, replace our scripts with the mmap'd version to save dirty memory.
-    ASSERT(mainScript.get() == m_script.get()); // Do a memcmp to make sure the scripts are identical.
+    ASSERT(mainScript == m_script); // Do a memcmp to make sure the scripts are identical.
     m_script = WTFMove(mainScript);
     for (auto& pair : importedScripts) {
         auto it = m_scriptResourceMap.find(pair.key);
@@ -252,7 +252,7 @@
         ASSERT(it != m_scriptResourceMap.end());
         if (it == m_scriptResourceMap.end())
             continue;
-        ASSERT(*it->value.script == *pair.value); // Do a memcmp to make sure the scripts are identical.
+        ASSERT(it->value.script == pair.value); // Do a memcmp to make sure the scripts are identical.
         it->value.script = WTFMove(pair.value);
     }
 }

Modified: trunk/Source/WebCore/workers/service/server/SWServerWorker.h (275442 => 275443)


--- trunk/Source/WebCore/workers/service/server/SWServerWorker.h	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebCore/workers/service/server/SWServerWorker.h	2021-04-02 21:53:30 UTC (rev 275443)
@@ -80,7 +80,7 @@
     SWServer* server() { return m_server.get(); }
     const ServiceWorkerRegistrationKey& registrationKey() const { return m_registrationKey; }
     const URL& scriptURL() const { return m_data.scriptURL; }
-    SharedBuffer& script() const { return m_script; }
+    const ScriptBuffer& script() const { return m_script; }
     const CertificateInfo& certificateInfo() const { return m_certificateInfo; }
     WorkerType type() const { return m_data.type; }
 
@@ -102,7 +102,7 @@
     WEBCORE_EXPORT Optional<ServiceWorkerClientData> findClientByIdentifier(const ServiceWorkerClientIdentifier&) const;
     void matchAll(const ServiceWorkerClientQueryOptions&, ServiceWorkerClientsMatchAllCallback&&);
     void setScriptResource(URL&&, ServiceWorkerContextData::ImportedScript&&);
-    void didSaveScriptsToDisk(Ref<SharedBuffer>&& mainScript, HashMap<URL, RefPtr<SharedBuffer>>&& importedScripts);
+    void didSaveScriptsToDisk(ScriptBuffer&& mainScript, HashMap<URL, ScriptBuffer>&& importedScripts);
 
     void skipWaiting();
     bool isSkipWaitingFlagSet() const { return m_isSkipWaitingFlagSet; }
@@ -128,7 +128,7 @@
     void didFailHeartBeatCheck();
 
 private:
-    SWServerWorker(SWServer&, SWServerRegistration&, const URL&, SharedBuffer& script, const CertificateInfo&, const ContentSecurityPolicyResponseHeaders&, String&& referrerPolicy, WorkerType, ServiceWorkerIdentifier, HashMap<URL, ServiceWorkerContextData::ImportedScript>&&);
+    SWServerWorker(SWServer&, SWServerRegistration&, const URL&, const ScriptBuffer&, const CertificateInfo&, const ContentSecurityPolicyResponseHeaders&, String&& referrerPolicy, WorkerType, ServiceWorkerIdentifier, HashMap<URL, ServiceWorkerContextData::ImportedScript>&&);
 
     void callWhenActivatedHandler(bool success);
 
@@ -141,7 +141,7 @@
     ServiceWorkerRegistrationKey m_registrationKey;
     WeakPtr<SWServerRegistration> m_registration;
     ServiceWorkerData m_data;
-    Ref<SharedBuffer> m_script;
+    ScriptBuffer m_script;
     CertificateInfo m_certificateInfo;
     ContentSecurityPolicyResponseHeaders m_contentSecurityPolicy;
     String m_referrerPolicy;

Modified: trunk/Source/WebKit/ChangeLog (275442 => 275443)


--- trunk/Source/WebKit/ChangeLog	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebKit/ChangeLog	2021-04-02 21:53:30 UTC (rev 275443)
@@ -1,5 +1,43 @@
 2021-04-02  Chris Dumez  <[email protected]>
 
+        Introduce ScriptBuffer class to wrap SharedBuffer containing a script
+        https://bugs.webkit.org/show_bug.cgi?id=224092
+
+        Reviewed by Yusuke Suzuki and Geoff Garen.
+
+        Introduce ScriptBuffer class to wrap SharedBuffer containing a script. We started using SharedBuffer to represent
+        worker scripts instead of String, so that they can hold file mapped data and be shared across processes.
+        This patch introduces a new ScriptBuffer to wrap those SharedBuffers. The type makes it clearer what type of
+        data we're dealing with. The helper functions used to convert between String and SharedBuffer can now simply
+        be member functions on ScriptBuffer. This also simplifies IPC code.
+
+        * NetworkProcess/ServiceWorker/WebSWServerToContextConnection.cpp:
+        (WebKit::WebSWServerToContextConnection::didSaveScriptsToDisk):
+        * NetworkProcess/ServiceWorker/WebSWServerToContextConnection.h:
+        Use ScriptBuffer instead SharedBuffer.
+
+        * Shared/WebCoreArgumentCoders.cpp:
+        (IPC::tryConvertToShareableResourceHandle):
+        (IPC::decodeScriptBufferAsShareableResourceHandle):
+        (IPC::ArgumentCoder<WebCore::ScriptBuffer>::encode):
+        (IPC::ArgumentCoder<WebCore::ScriptBuffer>::decode):
+        * Shared/WebCoreArgumentCoders.h:
+        - Add IPC encoder / decoder for ScriptBuffer which tries to encode / decode as a ShareableResource whenever
+          possible (single segment that is file mapped). This logic used to be in the ServiceWorkerContextData
+          coders. Now that the logic is in the ScriptBuffer coder, the ServiceWorkerContextData encoding / decoding
+          becomes much simpler.
+        - Moved ServiceWorkerContextData coders from WebCoreArgumentCoders back to its class in WebCore, now that
+          they no longer need to deal with ShareableResource directly.
+
+        * WebProcess/Storage/WebSWContextManagerConnection.cpp:
+        (WebKit::WebSWContextManagerConnection::didSaveScriptsToDisk):
+        * WebProcess/Storage/WebSWContextManagerConnection.h:
+        * WebProcess/Storage/WebSWContextManagerConnection.messages.in:
+        Send scripts over IPC as ScriptBuffer instead of using ShareableResource directly. The new IPC encoder /
+        decoder for ScriptBuffer takes care of using ShareableResource for us.
+
+2021-04-02  Chris Dumez  <[email protected]>
+
         Unreviewed, reverting r275434.
 
         Need to figure out a better strategy to chose the color

Modified: trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.cpp (275442 => 275443)


--- trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -107,19 +107,18 @@
     send(Messages::WebSWContextManagerConnection::TerminateWorker(serviceWorkerIdentifier));
 }
 
-void WebSWServerToContextConnection::didSaveScriptsToDisk(ServiceWorkerIdentifier serviceWorkerIdentifier, WebCore::SharedBuffer& script, const HashMap<URL, RefPtr<SharedBuffer>>& importedScripts)
+void WebSWServerToContextConnection::didSaveScriptsToDisk(ServiceWorkerIdentifier serviceWorkerIdentifier, const ScriptBuffer& script, const HashMap<URL, ScriptBuffer>& importedScripts)
 {
 #if ENABLE(SHAREABLE_RESOURCE) && PLATFORM(COCOA)
-    auto scriptHandle = IPC::tryConvertToShareableResourceHandle(script);
-    HashMap<URL, ShareableResource::Handle> importedScriptHandles;
+    // Send file-mapped ScriptBuffers over to the ServiceWorker process so that it can replace its heap-allocated copies and save on dirty memory.
+    auto scriptToSend = script.containsSingleFileMappedSegment() ? script : ScriptBuffer();
+    HashMap<URL, ScriptBuffer> importedScriptsToSend;
     for (auto& pair : importedScripts) {
-        auto handle = IPC::tryConvertToShareableResourceHandle(*pair.value);
-        if (handle.isNull())
-            continue;
-        importedScriptHandles.add(pair.key, WTFMove(handle));
+        if (pair.value.containsSingleFileMappedSegment())
+            importedScriptsToSend.add(pair.key, pair.value);
     }
-    if (!scriptHandle.isNull() || !importedScriptHandles.isEmpty())
-        send(Messages::WebSWContextManagerConnection::DidSaveScriptsToDisk { serviceWorkerIdentifier, scriptHandle, importedScriptHandles });
+    if (scriptToSend || !importedScriptsToSend.isEmpty())
+        send(Messages::WebSWContextManagerConnection::DidSaveScriptsToDisk { serviceWorkerIdentifier, scriptToSend, importedScriptsToSend });
 #else
     UNUSED_PARAM(script);
     UNUSED_PARAM(importedScripts);

Modified: trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.h (275442 => 275443)


--- trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.h	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.h	2021-04-02 21:53:30 UTC (rev 275443)
@@ -88,7 +88,7 @@
     void fireInstallEvent(WebCore::ServiceWorkerIdentifier) final;
     void fireActivateEvent(WebCore::ServiceWorkerIdentifier) final;
     void terminateWorker(WebCore::ServiceWorkerIdentifier) final;
-    void didSaveScriptsToDisk(WebCore::ServiceWorkerIdentifier, WebCore::SharedBuffer& script, const HashMap<URL, RefPtr<WebCore::SharedBuffer>>& importedScripts) final;
+    void didSaveScriptsToDisk(WebCore::ServiceWorkerIdentifier, const WebCore::ScriptBuffer&, const HashMap<URL, WebCore::ScriptBuffer>& importedScripts) final;
     void findClientByIdentifierCompleted(uint64_t requestIdentifier, const Optional<WebCore::ServiceWorkerClientData>&, bool hasSecurityError) final;
     void matchAllCompleted(uint64_t requestIdentifier, const Vector<WebCore::ServiceWorkerClientData>&) final;
 

Modified: trunk/Source/WebKit/Shared/WebCoreArgumentCoders.cpp (275442 => 275443)


--- trunk/Source/WebKit/Shared/WebCoreArgumentCoders.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebKit/Shared/WebCoreArgumentCoders.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -28,6 +28,7 @@
 
 #include "DataReference.h"
 #include "ShareableBitmap.h"
+#include "ShareableResource.h"
 #include "SharedBufferDataReference.h"
 #include "StreamConnectionEncoder.h"
 #include <_javascript_Core/GenericTypedArrayViewInlines.h>
@@ -73,6 +74,7 @@
 #include <WebCore/ResourceLoadStatistics.h>
 #include <WebCore/ResourceRequest.h>
 #include <WebCore/ResourceResponse.h>
+#include <WebCore/ScriptBuffer.h>
 #include <WebCore/ScrollingConstraints.h>
 #include <WebCore/ScrollingCoordinator.h>
 #include <WebCore/SearchPopupMenu.h>
@@ -2829,144 +2831,8 @@
     return true;
 }
 
-static void encodeServiceWorkerContextDataScript(Encoder& encoder, SharedBuffer& script)
-{
-#if ENABLE(SHAREABLE_RESOURCE) && PLATFORM(COCOA)
-    auto handle = tryConvertToShareableResourceHandle(script);
-    bool isShareableResourceHandle = !handle.isNull();
-    encoder << isShareableResourceHandle;
-    if (isShareableResourceHandle) {
-        encoder << handle;
-        return;
-    }
 #endif
-    encoder << makeRef(script);
-}
 
-static Optional<Ref<SharedBuffer>> decodeServiceWorkerContextDataScript(Decoder& decoder)
-{
-#if ENABLE(SHAREABLE_RESOURCE) && PLATFORM(COCOA)
-    Optional<bool> isShareableResourceHandle;
-    decoder >> isShareableResourceHandle;
-    if (!isShareableResourceHandle)
-        return WTF::nullopt;
-    if (*isShareableResourceHandle) {
-        ShareableResource::Handle handle;
-        if (!decoder.decode(handle) || handle.isNull())
-            return WTF::nullopt;
-        auto buffer = handle.tryWrapInSharedBuffer();
-        if (!buffer)
-            return WTF::nullopt;
-        return buffer.releaseNonNull();
-    }
-#endif
-    Optional<Ref<SharedBuffer>> script;
-    decoder >> script;
-    return script;
-}
-
-void ArgumentCoder<ServiceWorkerContextData::ImportedScript>::encode(Encoder& encoder, const ServiceWorkerContextData::ImportedScript& importedScript)
-{
-    encodeServiceWorkerContextDataScript(encoder, *importedScript.script);
-    encoder << importedScript.responseURL << importedScript.mimeType;
-}
-
-Optional<ServiceWorkerContextData::ImportedScript> ArgumentCoder<ServiceWorkerContextData::ImportedScript>::decode(Decoder& decoder)
-{
-    auto script = decodeServiceWorkerContextDataScript(decoder);
-    if (!script)
-        return WTF::nullopt;
-
-    Optional<URL> responseURL;
-    decoder >> responseURL;
-    if (!responseURL)
-        return WTF::nullopt;
-
-    Optional<String> mimeType;
-    decoder >> mimeType;
-    if (!mimeType)
-        return WTF::nullopt;
-
-    return {{
-        WTFMove(*script),
-        WTFMove(*responseURL),
-        WTFMove(*mimeType)
-    }};
-}
-
-void ArgumentCoder<ServiceWorkerContextData>::encode(Encoder& encoder, const ServiceWorkerContextData& data)
-{
-    encodeServiceWorkerContextDataScript(encoder, data.script);
-    encoder << data.jobDataIdentifier << data.registration << data.serviceWorkerIdentifier << data.contentSecurityPolicy << data.referrerPolicy
-        << data.scriptURL << data.workerType << data.loadedFromDisk << data.scriptResourceMap << data.certificateInfo;
-}
-
-Optional<ServiceWorkerContextData> ArgumentCoder<ServiceWorkerContextData>::decode(Decoder& decoder)
-{
-    auto script = decodeServiceWorkerContextDataScript(decoder);
-    if (!script)
-        return WTF::nullopt;
-
-    Optional<Optional<ServiceWorkerJobDataIdentifier>> jobDataIdentifier;
-    decoder >> jobDataIdentifier;
-    if (!jobDataIdentifier)
-        return WTF::nullopt;
-
-    Optional<ServiceWorkerRegistrationData> registration;
-    decoder >> registration;
-    if (!registration)
-        return WTF::nullopt;
-
-    auto serviceWorkerIdentifier = ServiceWorkerIdentifier::decode(decoder);
-    if (!serviceWorkerIdentifier)
-        return WTF::nullopt;
-
-    ContentSecurityPolicyResponseHeaders contentSecurityPolicy;
-    if (!decoder.decode(contentSecurityPolicy))
-        return WTF::nullopt;
-
-    String referrerPolicy;
-    if (!decoder.decode(referrerPolicy))
-        return WTF::nullopt;
-
-    URL scriptURL;
-    if (!decoder.decode(scriptURL))
-        return WTF::nullopt;
-
-    WorkerType workerType;
-    if (!decoder.decode(workerType))
-        return WTF::nullopt;
-
-    bool loadedFromDisk;
-    if (!decoder.decode(loadedFromDisk))
-        return WTF::nullopt;
-
-    HashMap<URL, ServiceWorkerContextData::ImportedScript> scriptResourceMap;
-    if (!decoder.decode(scriptResourceMap))
-        return WTF::nullopt;
-
-    Optional<CertificateInfo> certificateInfo;
-    decoder >> certificateInfo;
-    if (!certificateInfo)
-        return WTF::nullopt;
-
-    return {{
-        WTFMove(*jobDataIdentifier),
-        WTFMove(*registration),
-        WTFMove(*serviceWorkerIdentifier),
-        WTFMove(*script),
-        WTFMove(*certificateInfo),
-        WTFMove(contentSecurityPolicy),
-        WTFMove(referrerPolicy),
-        WTFMove(scriptURL),
-        workerType,
-        loadedFromDisk,
-        WTFMove(scriptResourceMap)
-    }};
-}
-
-#endif
-
 #if ENABLE(CSS_SCROLL_SNAP)
 
 void ArgumentCoder<ScrollOffsetRange<float>>::encode(Encoder& encoder, const ScrollOffsetRange<float>& range)
@@ -3204,15 +3070,12 @@
 }
 
 #if ENABLE(SHAREABLE_RESOURCE) && PLATFORM(COCOA)
-ShareableResource::Handle tryConvertToShareableResourceHandle(SharedBuffer& buffer)
+static ShareableResource::Handle tryConvertToShareableResourceHandle(const ScriptBuffer& script)
 {
-    if (!buffer.hasOneSegment())
+    if (!script.containsSingleFileMappedSegment())
         return ShareableResource::Handle { };
 
-    auto& segment = buffer.begin()->segment;
-    if (!segment->containsMappedFileData())
-        return ShareableResource::Handle { };
-
+    auto& segment = script.buffer()->begin()->segment;
     auto sharedMemory = SharedMemory::wrapMap(const_cast<char*>(segment->data()), segment->size(), SharedMemory::Protection::ReadOnly);
     if (!sharedMemory)
         return ShareableResource::Handle { };
@@ -3225,8 +3088,51 @@
     shareableResource->createHandle(shareableResourceHandle);
     return shareableResourceHandle;
 }
+
+static Optional<WebCore::ScriptBuffer> decodeScriptBufferAsShareableResourceHandle(Decoder& decoder)
+{
+    ShareableResource::Handle handle;
+    if (!decoder.decode(handle) || handle.isNull())
+        return WTF::nullopt;
+    auto buffer = handle.tryWrapInSharedBuffer();
+    if (!buffer)
+        return WTF::nullopt;
+    return WebCore::ScriptBuffer { WTFMove(buffer) };
+}
 #endif
 
+void ArgumentCoder<WebCore::ScriptBuffer>::encode(Encoder& encoder, const WebCore::ScriptBuffer& script)
+{
+#if ENABLE(SHAREABLE_RESOURCE) && PLATFORM(COCOA)
+    auto handle = tryConvertToShareableResourceHandle(script);
+    bool isShareableResourceHandle = !handle.isNull();
+    encoder << isShareableResourceHandle;
+    if (isShareableResourceHandle) {
+        encoder << handle;
+        return;
+    }
+#endif
+    encodeSharedBuffer(encoder, script.buffer());
+}
+
+Optional<WebCore::ScriptBuffer> ArgumentCoder<WebCore::ScriptBuffer>::decode(Decoder& decoder)
+{
+#if ENABLE(SHAREABLE_RESOURCE) && PLATFORM(COCOA)
+    Optional<bool> isShareableResourceHandle;
+    decoder >> isShareableResourceHandle;
+    if (!isShareableResourceHandle)
+        return WTF::nullopt;
+    if (*isShareableResourceHandle)
+        return decodeScriptBufferAsShareableResourceHandle(decoder);
+#endif
+
+    RefPtr<SharedBuffer> buffer;
+    if (!decodeSharedBuffer(decoder, buffer))
+        return WTF::nullopt;
+
+    return WebCore::ScriptBuffer { WTFMove(buffer) };
+}
+
 #if ENABLE(ENCRYPTED_MEDIA)
 void ArgumentCoder<WebCore::CDMInstanceSession::Message>::encode(Encoder& encoder, const WebCore::CDMInstanceSession::Message& message)
 {

Modified: trunk/Source/WebKit/Shared/WebCoreArgumentCoders.h (275442 => 275443)


--- trunk/Source/WebKit/Shared/WebCoreArgumentCoders.h	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebKit/Shared/WebCoreArgumentCoders.h	2021-04-02 21:53:30 UTC (rev 275443)
@@ -26,7 +26,6 @@
 #pragma once
 
 #include "ArgumentCoders.h"
-#include "ShareableResource.h"
 #include <WebCore/AutoplayEvent.h>
 #include <WebCore/ColorSpace.h>
 #include <WebCore/DiagnosticLoggingClient.h>
@@ -42,7 +41,6 @@
 #include <WebCore/RenderingMode.h>
 #include <WebCore/ScrollSnapOffsetsInfo.h>
 #include <WebCore/SerializedPlatformDataCueValue.h>
-#include <WebCore/ServiceWorkerContextData.h>
 #include <WebCore/ServiceWorkerTypes.h>
 #include <WebCore/StoredCredentialsPolicy.h>
 #include <WebCore/WorkerType.h>
@@ -122,6 +120,7 @@
 class ResourceError;
 class ResourceRequest;
 class ResourceResponse;
+class ScriptBuffer;
 class SecurityOrigin;
 class SharedBuffer;
 class SpringTimingFunction;
@@ -737,16 +736,6 @@
     static WARN_UNUSED_RETURN bool decode(Decoder&, WebCore::ServiceWorkerOrClientIdentifier&);
 };
 
-template<> struct ArgumentCoder<WebCore::ServiceWorkerContextData> {
-    static void encode(Encoder&, const WebCore::ServiceWorkerContextData&);
-    static Optional<WebCore::ServiceWorkerContextData> decode(Decoder&);
-};
-
-template<> struct ArgumentCoder<WebCore::ServiceWorkerContextData::ImportedScript> {
-    static void encode(Encoder&, const WebCore::ServiceWorkerContextData::ImportedScript&);
-    static Optional<WebCore::ServiceWorkerContextData::ImportedScript> decode(Decoder&);
-};
-
 #endif
 
 #if ENABLE(CSS_SCROLL_SNAP)
@@ -808,11 +797,10 @@
     static Optional<Ref<WebCore::SharedBuffer>> decode(Decoder&);
 };
 
-#if ENABLE(SHAREABLE_RESOURCE) && PLATFORM(COCOA)
-// If the SharedBuffer contains a single segment and the segment is MappedFileData, then convert it into
-// a ShareableResource handle so that it can be sent over IPC and shared with another process.
-WebKit::ShareableResource::Handle tryConvertToShareableResourceHandle(WebCore::SharedBuffer&);
-#endif
+template<> struct ArgumentCoder<WebCore::ScriptBuffer> {
+    static void encode(Encoder&, const WebCore::ScriptBuffer&);
+    static Optional<WebCore::ScriptBuffer> decode(Decoder&);
+};
 
 #if ENABLE(ENCRYPTED_MEDIA)
 template<> struct ArgumentCoder<WebCore::CDMInstanceSession::Message> {

Modified: trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.cpp (275442 => 275443)


--- trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.cpp	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.cpp	2021-04-02 21:53:30 UTC (rev 275443)
@@ -263,22 +263,9 @@
 }
 
 #if ENABLE(SHAREABLE_RESOURCE) && PLATFORM(COCOA)
-void WebSWContextManagerConnection::didSaveScriptsToDisk(WebCore::ServiceWorkerIdentifier identifier, const ShareableResource::Handle& scriptHandle, const HashMap<URL, ShareableResource::Handle>& importedScriptHandles)
+void WebSWContextManagerConnection::didSaveScriptsToDisk(WebCore::ServiceWorkerIdentifier identifier, ScriptBuffer&& script, HashMap<URL, ScriptBuffer>&& importedScripts)
 {
-    auto toSharedBuffer = [](const ShareableResource::Handle& handle) -> RefPtr<SharedBuffer> {
-        if (handle.isNull())
-            return nullptr;
-        auto sharedBuffer = handle.tryWrapInSharedBuffer();
-        if (!sharedBuffer)
-            RELEASE_LOG_ERROR(ServiceWorker, "WebSWContextManagerConnection::didSaveScriptsToDisk: Failed to wrap ShareableResource handle in a SharedBuffer");
-        return sharedBuffer;
-    };
-    HashMap<URL, RefPtr<SharedBuffer>> importedScripts;
-    for (auto& pair : importedScriptHandles) {
-        if (auto sharedBuffer = toSharedBuffer(pair.value))
-            importedScripts.add(pair.key, WTFMove(sharedBuffer));
-    }
-    SWContextManager::singleton().didSaveScriptsToDisk(identifier, toSharedBuffer(scriptHandle), WTFMove(importedScripts));
+    SWContextManager::singleton().didSaveScriptsToDisk(identifier, WTFMove(script), WTFMove(importedScripts));
 }
 #endif
 

Modified: trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.h (275442 => 275443)


--- trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.h	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.h	2021-04-02 21:53:30 UTC (rev 275443)
@@ -92,7 +92,7 @@
     void fireActivateEvent(WebCore::ServiceWorkerIdentifier);
     void terminateWorker(WebCore::ServiceWorkerIdentifier);
 #if ENABLE(SHAREABLE_RESOURCE) && PLATFORM(COCOA)
-    void didSaveScriptsToDisk(WebCore::ServiceWorkerIdentifier, const ShareableResource::Handle& script, const HashMap<URL, ShareableResource::Handle>& importedScripts);
+    void didSaveScriptsToDisk(WebCore::ServiceWorkerIdentifier, WebCore::ScriptBuffer&&, HashMap<URL, WebCore::ScriptBuffer>&& importedScripts);
 #endif
     void findClientByIdentifierCompleted(uint64_t requestIdentifier, Optional<WebCore::ServiceWorkerClientData>&&, bool hasSecurityError);
     void matchAllCompleted(uint64_t matchAllRequestIdentifier, Vector<WebCore::ServiceWorkerClientData>&&);

Modified: trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.messages.in (275442 => 275443)


--- trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.messages.in	2021-04-02 21:39:10 UTC (rev 275442)
+++ trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.messages.in	2021-04-02 21:53:30 UTC (rev 275443)
@@ -32,7 +32,7 @@
     FireActivateEvent(WebCore::ServiceWorkerIdentifier identifier)
     TerminateWorker(WebCore::ServiceWorkerIdentifier identifier)
 #if ENABLE(SHAREABLE_RESOURCE) && PLATFORM(COCOA)
-    DidSaveScriptsToDisk(WebCore::ServiceWorkerIdentifier serviceWorkerIdentifier, WebKit::ShareableResource::Handle script, HashMap<URL, WebKit::ShareableResource::Handle> importedScripts);
+    DidSaveScriptsToDisk(WebCore::ServiceWorkerIdentifier serviceWorkerIdentifier, WebCore::ScriptBuffer script, HashMap<URL, WebCore::ScriptBuffer> importedScripts);
 #endif
     FindClientByIdentifierCompleted(uint64_t clientIdRequestIdentifier, Optional<WebCore::ServiceWorkerClientData> data, bool hasSecurityError)
     MatchAllCompleted(uint64_t matchAllRequestIdentifier, Vector<WebCore::ServiceWorkerClientData> clientsData)
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to