| Differences between
and this patch
- a/PerformanceTests/ChangeLog +10 lines
Lines 1-3 a/PerformanceTests/ChangeLog_sec1
1
2021-12-02  Jean-Yves Avenard  <jya@apple.com>
2
3
        Distinguish contiguous SharedBuffer from non-contiguous one and guarantee immutability: part 3
4
        https://bugs.webkit.org/show_bug.cgi?id=233677
5
6
        Reviewed by NOBODY (OOPS!).
7
8
        * DecoderTest/DecoderTest/main.mm:
9
        (main):
10
1
2021-11-21  Cathie Chen  <cathiechen@igalia.com>
11
2021-11-21  Cathie Chen  <cathiechen@igalia.com>
2
12
3
        [Performance test][css-contain] Add case to test contain: layout inside a complex document
13
        [Performance test][css-contain] Add case to test contain: layout inside a complex document
- a/Source/JavaScriptCore/ChangeLog +14 lines
Lines 1-3 a/Source/JavaScriptCore/ChangeLog_sec1
1
2021-12-03  Jean-Yves Avenard  <jya@apple.com>
2
3
        Rename SharedBuffer classes.
4
        https://bugs.webkit.org/show_bug.cgi?id=233677
5
        rdar://problem/85963900
6
7
        Reviewed by NOBODY (OOPS!).
8
9
        SharedBuffer are renamed FragmentedSharedBuffer and
10
        ContiguousSharedBuffer to SharedBuffer to better reflect their actual
11
        types.
12
13
        * runtime/ArrayBuffer.h:
14
1
2021-12-03  Keith Miller  <keith_miller@apple.com>
15
2021-12-03  Keith Miller  <keith_miller@apple.com>
2
16
3
        Remove StructureIDBlob
17
        Remove StructureIDBlob
- a/Source/JavaScriptCore/runtime/ArrayBuffer.h -1 / +1 lines
Lines 129-135 public: a/Source/JavaScriptCore/runtime/ArrayBuffer.h_sec1
129
    JS_EXPORT_PRIVATE static RefPtr<ArrayBuffer> tryCreate(ArrayBuffer&);
129
    JS_EXPORT_PRIVATE static RefPtr<ArrayBuffer> tryCreate(ArrayBuffer&);
130
    JS_EXPORT_PRIVATE static RefPtr<ArrayBuffer> tryCreate(const void* source, size_t byteLength);
130
    JS_EXPORT_PRIVATE static RefPtr<ArrayBuffer> tryCreate(const void* source, size_t byteLength);
131
131
132
    // Only for use by Uint8ClampedArray::tryCreateUninitialized and SharedBuffer::tryCreateArrayBuffer.
132
    // Only for use by Uint8ClampedArray::tryCreateUninitialized and FragmentedSharedBuffer::tryCreateArrayBuffer.
133
    JS_EXPORT_PRIVATE static Ref<ArrayBuffer> createUninitialized(size_t numElements, unsigned elementByteSize);
133
    JS_EXPORT_PRIVATE static Ref<ArrayBuffer> createUninitialized(size_t numElements, unsigned elementByteSize);
134
    JS_EXPORT_PRIVATE static RefPtr<ArrayBuffer> tryCreateUninitialized(size_t numElements, unsigned elementByteSize);
134
    JS_EXPORT_PRIVATE static RefPtr<ArrayBuffer> tryCreateUninitialized(size_t numElements, unsigned elementByteSize);
135
135
- a/Source/WebCore/ChangeLog +1046 lines
Lines 1-3 a/Source/WebCore/ChangeLog_sec1
1
2021-12-07  Jean-Yves Avenard  <jya@apple.com>
2
3
        Make PreviewConverterProvider not modify the SharedBuffer once returned
4
        https://bugs.webkit.org/show_bug.cgi?id=233923
5
6
        Reviewed by NOBODY (OOPS!).
7
8
        No new tests (OOPS!).
9
10
        * loader/ios/LegacyPreviewLoader.h:
11
        * loader/ios/LegacyPreviewLoader.mm:
12
        (WebCore::LegacyPreviewLoader::previewConverterDidStartConverting):
13
        (WebCore::LegacyPreviewLoader::provideMainResourceForPreviewConverter):
14
        * platform/PreviewConverter.cpp:
15
        (WebCore::PreviewConverter::updateMainResource):
16
        * platform/PreviewConverterProvider.h:
17
18
2021-12-05  Jean-Yves Avenard  <jya@apple.com>
19
20
        SourceBufferParser should be using contiguous SharedBuffer
21
        https://bugs.webkit.org/show_bug.cgi?id=233865
22
        rdar://problem/86085253
23
24
        Reviewed by NOBODY (OOPS!).
25
26
        Covered by existing tests, no observable differences.
27
28
        * Modules/mediasource/SourceBuffer.cpp:
29
        (WebCore::SourceBuffer::appendBufferTimerFired):
30
        * Modules/mediasource/SourceBuffer.h:
31
        * platform/audio/cocoa/AudioFileReaderCocoa.cpp:
32
        * platform/graphics/SourceBufferPrivate.cpp:
33
        (WebCore::SourceBufferPrivate::append):
34
        * platform/graphics/SourceBufferPrivate.h:
35
        * platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.h:
36
        * platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.mm:
37
        (WebCore::SourceBufferPrivateAVFObjC::append):
38
        * platform/graphics/cocoa/SourceBufferParser.cpp:
39
        (WebCore::SourceBufferParser::Segment::Segment):
40
        (WebCore::SourceBufferParser::Segment::size const):
41
        (WebCore::SourceBufferParser::Segment::read const):
42
        (WebCore::SourceBufferParser::Segment::takeSharedBuffer):
43
        (WebCore::SourceBufferParser::Segment::getSharedBuffer const):
44
        * platform/graphics/cocoa/SourceBufferParser.h:
45
        * platform/graphics/cocoa/SourceBufferParserWebM.cpp:
46
47
2021-12-03  Jean-Yves Avenard  <jya@apple.com>
48
49
        Rename SharedBuffer classes.
50
        https://bugs.webkit.org/show_bug.cgi?id=233677
51
        rdar://problem/85963900
52
53
        Reviewed by NOBODY (OOPS!).
54
55
        SharedBuffer are renamed FragmentedSharedBuffer and
56
        ContiguousSharedBuffer to SharedBuffer to better reflect their actual
57
        types.
58
59
        Rename only, no change in behaviour.
60
61
        * Modules/async-clipboard/ClipboardImageReader.cpp:
62
        * Modules/async-clipboard/ClipboardImageReader.h:
63
        * Modules/async-clipboard/ClipboardItemBindingsDataSource.cpp:
64
        * Modules/async-clipboard/ClipboardItemBindingsDataSource.h:
65
        * Modules/async-clipboard/ios/ClipboardImageReaderIOS.mm:
66
        * Modules/async-clipboard/mac/ClipboardImageReaderMac.mm:
67
        * Modules/cache/CacheStorageConnection.cpp:
68
        * Modules/cache/DOMCache.cpp:
69
        * Modules/cache/DOMCache.h:
70
        * Modules/cache/DOMCacheEngine.cpp:
71
        * Modules/cache/DOMCacheEngine.h:
72
        * Modules/encryptedmedia/CDM.cpp:
73
        * Modules/encryptedmedia/CDM.h:
74
        * Modules/encryptedmedia/CDMClient.h:
75
        * Modules/encryptedmedia/InitDataRegistry.cpp:
76
        * Modules/encryptedmedia/InitDataRegistry.h:
77
        * Modules/encryptedmedia/MediaKeySession.cpp:
78
        * Modules/encryptedmedia/MediaKeySession.h:
79
        * Modules/encryptedmedia/MediaKeyStatusMap.cpp:
80
        * Modules/encryptedmedia/MediaKeyStatusMap.h:
81
        * Modules/encryptedmedia/MediaKeys.cpp:
82
        * Modules/encryptedmedia/MediaKeys.h:
83
        * Modules/fetch/FetchBody.cpp:
84
        * Modules/fetch/FetchBody.h:
85
        * Modules/fetch/FetchBodyConsumer.cpp:
86
        * Modules/fetch/FetchBodyConsumer.h:
87
        * Modules/fetch/FetchLoader.cpp:
88
        * Modules/fetch/FetchLoader.h:
89
        * Modules/fetch/FetchResponse.cpp:
90
        * Modules/fetch/FetchResponse.h:
91
        * Modules/highlight/AppHighlight.h:
92
        * Modules/highlight/AppHighlightRangeData.cpp:
93
        * Modules/highlight/AppHighlightRangeData.h:
94
        * Modules/highlight/AppHighlightStorage.cpp:
95
        * Modules/highlight/AppHighlightStorage.h:
96
        * Modules/indexeddb/server/IDBSerialization.cpp:
97
        * Modules/indexeddb/server/IDBSerialization.h:
98
        * Modules/mediarecorder/MediaRecorder.cpp:
99
        * Modules/mediarecorder/MediaRecorder.h:
100
        * Modules/mediasession/MediaMetadata.cpp:
101
        * Modules/mediasource/SourceBuffer.cpp:
102
        * Modules/mediasource/SourceBuffer.h:
103
        * Modules/mediastream/RTCDataChannelRemoteHandler.h:
104
        * Modules/mediastream/libwebrtc/LibWebRTCDataChannelHandler.cpp:
105
        * Modules/mediastream/libwebrtc/LibWebRTCDataChannelHandler.h:
106
        * Modules/streams/ReadableStreamSink.h:
107
        * bindings/js/JSDOMGlobalObject.cpp:
108
        * bindings/js/ScriptBufferSourceProvider.h:
109
        * bindings/js/SerializedScriptValue.h:
110
        * css/CSSFontFaceSource.cpp:
111
        * css/CSSFontFaceSource.h:
112
        * dom/DataTransfer.cpp:
113
        * editing/Editor.cpp:
114
        * editing/Editor.h:
115
        * editing/SerializedAttachmentData.h:
116
        * editing/WebContentReader.h:
117
        * editing/WebCorePasteboardFileReader.cpp:
118
        * editing/WebCorePasteboardFileReader.h:
119
        * editing/cocoa/EditorCocoa.mm:
120
        * editing/cocoa/HTMLConverter.mm:
121
        * editing/cocoa/WebContentReaderCocoa.mm:
122
        * editing/gtk/WebContentReaderGtk.cpp:
123
        * editing/mac/EditorMac.mm:
124
        * fileapi/Blob.h:
125
        * fileapi/NetworkSendQueue.cpp:
126
        * fileapi/NetworkSendQueue.h:
127
        * html/FTPDirectoryDocument.cpp:
128
        * html/HTMLAttachmentElement.cpp:
129
        * html/HTMLAttachmentElement.h:
130
        * html/HTMLMediaElement.cpp:
131
        * html/HTMLMediaElement.h:
132
        * html/ImageDocument.cpp:
133
        * inspector/InspectorInstrumentation.cpp:
134
        * inspector/InspectorInstrumentation.h:
135
        * inspector/InspectorInstrumentationWebKit.cpp:
136
        * inspector/InspectorInstrumentationWebKit.h:
137
        * inspector/NetworkResourcesData.cpp:
138
        * inspector/NetworkResourcesData.h:
139
        * inspector/agents/InspectorNetworkAgent.cpp:
140
        * inspector/agents/InspectorNetworkAgent.h:
141
        * inspector/agents/InspectorPageAgent.cpp:
142
        * inspector/agents/InspectorPageAgent.h:
143
        * loader/ContentFilter.cpp:
144
        * loader/CrossOriginPreflightChecker.cpp:
145
        * loader/DocumentLoader.cpp:
146
        * loader/DocumentLoader.h:
147
        * loader/DocumentThreadableLoader.cpp:
148
        * loader/EmptyClients.cpp:
149
        * loader/FrameLoader.cpp:
150
        * loader/FrameLoader.h:
151
        * loader/FrameLoaderClient.h:
152
        * loader/LoaderStrategy.h:
153
        * loader/NetscapePlugInStreamLoader.cpp:
154
        * loader/NetscapePlugInStreamLoader.h:
155
        * loader/ResourceCryptographicDigest.cpp:
156
        * loader/ResourceCryptographicDigest.h:
157
        * loader/ResourceLoader.cpp:
158
        * loader/ResourceLoader.h:
159
        * loader/SubresourceLoader.cpp:
160
        * loader/SubresourceLoader.h:
161
        * loader/SubstituteData.h:
162
        * loader/SubstituteResource.h:
163
        * loader/appcache/ApplicationCacheHost.cpp:
164
        * loader/appcache/ApplicationCacheHost.h:
165
        * loader/appcache/ApplicationCacheResource.cpp:
166
        * loader/appcache/ApplicationCacheResource.h:
167
        * loader/appcache/ApplicationCacheStorage.cpp:
168
        * loader/appcache/ApplicationCacheStorage.h:
169
        * loader/archive/ArchiveFactory.cpp:
170
        * loader/archive/ArchiveFactory.h:
171
        * loader/archive/ArchiveResource.cpp:
172
        * loader/archive/ArchiveResource.h:
173
        * loader/archive/cf/LegacyWebArchive.cpp:
174
        * loader/archive/cf/LegacyWebArchive.h:
175
        * loader/archive/mhtml/MHTMLArchive.cpp:
176
        * loader/archive/mhtml/MHTMLArchive.h:
177
        * loader/archive/mhtml/MHTMLParser.cpp:
178
        * loader/archive/mhtml/MHTMLParser.h:
179
        * loader/cache/CachedApplicationManifest.cpp:
180
        * loader/cache/CachedApplicationManifest.h:
181
        * loader/cache/CachedCSSStyleSheet.cpp:
182
        * loader/cache/CachedCSSStyleSheet.h:
183
        * loader/cache/CachedFont.cpp:
184
        * loader/cache/CachedFont.h:
185
        * loader/cache/CachedImage.cpp:
186
        * loader/cache/CachedImage.h:
187
        * loader/cache/CachedRawResource.cpp:
188
        * loader/cache/CachedRawResource.h:
189
        * loader/cache/CachedResource.cpp:
190
        * loader/cache/CachedResource.h:
191
        * loader/cache/CachedSVGDocument.cpp:
192
        * loader/cache/CachedSVGDocument.h:
193
        * loader/cache/CachedSVGFont.cpp:
194
        * loader/cache/CachedSVGFont.h:
195
        * loader/cache/CachedScript.cpp:
196
        * loader/cache/CachedScript.h:
197
        * loader/cache/CachedTextTrack.cpp:
198
        * loader/cache/CachedTextTrack.h:
199
        * loader/cache/CachedXSLStyleSheet.cpp:
200
        * loader/cache/CachedXSLStyleSheet.h:
201
        * loader/cocoa/DiskCacheMonitorCocoa.h:
202
        * loader/cocoa/DiskCacheMonitorCocoa.mm:
203
        * loader/ios/LegacyPreviewLoader.h:
204
        * loader/ios/LegacyPreviewLoader.mm:
205
        * page/EditorClient.h:
206
        * page/Page.cpp:
207
        * page/PageSerializer.cpp:
208
        * page/PageSerializer.h:
209
        * page/ShareData.h:
210
        * page/ShareDataReader.cpp:
211
        * platform/KeyedCoding.h:
212
        * platform/NowPlayingManager.h:
213
        * platform/Pasteboard.cpp:
214
        * platform/Pasteboard.h:
215
        * platform/PasteboardCustomData.cpp:
216
        * platform/PasteboardCustomData.h:
217
        * platform/PasteboardStrategy.h:
218
        * platform/PasteboardWriterData.h:
219
        * platform/PlatformContentFilter.h:
220
        * platform/PlatformPasteboard.h:
221
        * platform/PreviewConverter.cpp:
222
        * platform/PreviewConverter.h:
223
        * platform/PreviewConverterClient.h:
224
        * platform/PreviewConverterProvider.h:
225
        * platform/PromisedAttachmentInfo.h:
226
        * platform/SharedBuffer.cpp:
227
        * platform/SharedBuffer.h:
228
        * platform/SharedBufferChunkReader.cpp:
229
        * platform/SharedBufferChunkReader.h:
230
        * platform/StaticPasteboard.cpp:
231
        * platform/StaticPasteboard.h:
232
        * platform/audio/NowPlayingInfo.h:
233
        * platform/audio/cocoa/AudioFileReaderCocoa.cpp:
234
        * platform/cf/KeyedEncoderCF.cpp:
235
        * platform/cf/KeyedEncoderCF.h:
236
        * platform/cf/SharedBufferCF.cpp:
237
        * platform/cocoa/NetworkExtensionContentFilter.h:
238
        * platform/cocoa/NetworkExtensionContentFilter.mm:
239
        * platform/cocoa/ParentalControlsContentFilter.h:
240
        * platform/cocoa/ParentalControlsContentFilter.mm:
241
        * platform/cocoa/PasteboardCocoa.mm:
242
        * platform/cocoa/SharedBufferCocoa.mm:
243
        * platform/encryptedmedia/CDMInstance.h:
244
        * platform/encryptedmedia/CDMInstanceSession.h:
245
        * platform/encryptedmedia/CDMPrivate.h:
246
        * platform/encryptedmedia/CDMProxy.cpp:
247
        * platform/encryptedmedia/CDMProxy.h:
248
        * platform/encryptedmedia/CDMUtilities.cpp:
249
        * platform/encryptedmedia/CDMUtilities.h:
250
        * platform/encryptedmedia/clearkey/CDMClearKey.cpp:
251
        * platform/encryptedmedia/clearkey/CDMClearKey.h:
252
        * platform/generic/KeyedEncoderGeneric.cpp:
253
        * platform/generic/KeyedEncoderGeneric.h:
254
        * platform/glib/KeyedEncoderGlib.cpp:
255
        * platform/glib/KeyedEncoderGlib.h:
256
        * platform/glib/SharedBufferGlib.cpp:
257
        * platform/graphics/Font.cpp:
258
        * platform/graphics/Font.h:
259
        * platform/graphics/FontPlatformData.h:
260
        * platform/graphics/Image.cpp:
261
        * platform/graphics/Image.h:
262
        * platform/graphics/ImageBackingStore.h:
263
        * platform/graphics/ImageDecoder.cpp:
264
        * platform/graphics/ImageDecoder.h:
265
        * platform/graphics/ImageSource.cpp:
266
        * platform/graphics/ImageSource.h:
267
        * platform/graphics/Model.cpp:
268
        * platform/graphics/Model.h:
269
        * platform/graphics/PlatformMediaResourceLoader.h:
270
        * platform/graphics/SourceBufferPrivate.cpp:
271
        * platform/graphics/SourceBufferPrivate.h:
272
        * platform/graphics/WOFFFileFormat.cpp:
273
        * platform/graphics/WOFFFileFormat.h:
274
        * platform/graphics/avfoundation/CDMFairPlayStreaming.cpp:
275
        * platform/graphics/avfoundation/CDMFairPlayStreaming.h:
276
        * platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.h:
277
        * platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm:
278
        * platform/graphics/avfoundation/objc/ImageDecoderAVFObjC.h:
279
        * platform/graphics/avfoundation/objc/ImageDecoderAVFObjC.mm:
280
        * platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.h:
281
        * platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm:
282
        * platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.h:
283
        * platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.mm:
284
        * platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.h:
285
        * platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm:
286
        * platform/graphics/cairo/FontCustomPlatformData.h:
287
        * platform/graphics/cg/ImageDecoderCG.cpp:
288
        * platform/graphics/cg/ImageDecoderCG.h:
289
        * platform/graphics/cocoa/FontPlatformDataCocoa.mm:
290
        * platform/graphics/cocoa/SourceBufferParser.cpp:
291
        * platform/graphics/cocoa/SourceBufferParser.h:
292
        * platform/graphics/cocoa/SourceBufferParserWebM.cpp:
293
        * platform/graphics/coretext/FontPlatformDataCoreText.cpp:
294
        * platform/graphics/displaylists/DisplayListItemBuffer.cpp:
295
        * platform/graphics/displaylists/DisplayListItemBuffer.h:
296
        * platform/graphics/freetype/FontCustomPlatformDataFreeType.cpp:
297
        * platform/graphics/freetype/FontPlatformDataFreeType.cpp:
298
        * platform/graphics/gstreamer/GStreamerCommon.cpp:
299
        * platform/graphics/gstreamer/GStreamerCommon.h:
300
        * platform/graphics/gstreamer/ImageDecoderGStreamer.cpp:
301
        * platform/graphics/gstreamer/ImageDecoderGStreamer.h:
302
        * platform/graphics/gstreamer/WebKitWebSourceGStreamer.cpp:
303
        * platform/graphics/gstreamer/eme/CDMProxyClearKey.h:
304
        * platform/graphics/gstreamer/eme/CDMThunder.cpp:
305
        * platform/graphics/gstreamer/eme/CDMThunder.h:
306
        * platform/graphics/gstreamer/eme/GStreamerEMEUtilities.cpp:
307
        * platform/graphics/gstreamer/eme/GStreamerEMEUtilities.h:
308
        * platform/graphics/mac/FontCustomPlatformData.cpp:
309
        * platform/graphics/mac/FontCustomPlatformData.h:
310
        * platform/graphics/opentype/OpenTypeMathData.cpp:
311
        * platform/graphics/opentype/OpenTypeMathData.h:
312
        * platform/graphics/opentype/OpenTypeTypes.h:
313
        * platform/graphics/opentype/OpenTypeUtilities.cpp:
314
        * platform/graphics/opentype/OpenTypeUtilities.h:
315
        * platform/graphics/opentype/OpenTypeVerticalData.cpp:
316
        * platform/graphics/win/DirectWriteUtilities.h:
317
        * platform/graphics/win/FontCustomPlatformData.cpp:
318
        * platform/graphics/win/FontCustomPlatformData.h:
319
        * platform/graphics/win/FontCustomPlatformDataCairo.cpp:
320
        * platform/graphics/win/FontPlatformDataCairoWin.cpp:
321
        * platform/graphics/win/FontPlatformDataWin.cpp:
322
        * platform/graphics/win/ImageDecoderDirect2D.cpp:
323
        * platform/graphics/win/ImageDecoderDirect2D.h:
324
        * platform/graphics/win/ImageWin.cpp:
325
        * platform/gtk/SelectionData.h:
326
        * platform/image-decoders/ScalableImageDecoder.cpp:
327
        * platform/image-decoders/ScalableImageDecoder.h:
328
        * platform/image-decoders/avif/AVIFImageReader.cpp:
329
        * platform/image-decoders/avif/AVIFImageReader.h:
330
        * platform/image-decoders/bmp/BMPImageDecoder.cpp:
331
        * platform/image-decoders/bmp/BMPImageDecoder.h:
332
        * platform/image-decoders/bmp/BMPImageReader.h:
333
        * platform/image-decoders/cairo/ImageBackingStoreCairo.cpp:
334
        * platform/image-decoders/gif/GIFImageDecoder.cpp:
335
        * platform/image-decoders/gif/GIFImageDecoder.h:
336
        * platform/image-decoders/gif/GIFImageReader.h:
337
        * platform/image-decoders/ico/ICOImageDecoder.cpp:
338
        * platform/image-decoders/ico/ICOImageDecoder.h:
339
        * platform/image-decoders/jpeg/JPEGImageDecoder.cpp:
340
        * platform/image-decoders/jpeg/JPEGImageDecoder.h:
341
        * platform/image-decoders/jpeg2000/JPEG2000ImageDecoder.cpp:
342
        * platform/image-decoders/png/PNGImageDecoder.cpp:
343
        * platform/image-decoders/webp/WEBPImageDecoder.cpp:
344
        * platform/image-decoders/webp/WEBPImageDecoder.h:
345
        * platform/ios/PasteboardIOS.mm:
346
        * platform/ios/PlatformPasteboardIOS.mm:
347
        * platform/mac/PasteboardMac.mm:
348
        * platform/mac/PlatformPasteboardMac.mm:
349
        * platform/mediarecorder/MediaRecorderPrivate.h:
350
        * platform/mediarecorder/MediaRecorderPrivateMock.cpp:
351
        * platform/mediarecorder/cocoa/MediaRecorderPrivateWriterCocoa.h:
352
        * platform/mediarecorder/cocoa/MediaRecorderPrivateWriterCocoa.mm:
353
        * platform/network/DataURLDecoder.h:
354
        * platform/network/FormData.cpp:
355
        * platform/network/FormData.h:
356
        * platform/network/ResourceHandle.h:
357
        * platform/network/ResourceHandleClient.cpp:
358
        * platform/network/ResourceHandleClient.h:
359
        * platform/network/cf/ResourceHandleCFURLConnectionDelegateWithOperationQueue.cpp:
360
        * platform/network/cocoa/RangeResponseGenerator.mm:
361
        * platform/network/cocoa/WebCoreNSURLSession.h:
362
        * platform/network/cocoa/WebCoreNSURLSession.mm:
363
        * platform/network/curl/CurlDownload.cpp:
364
        * platform/network/curl/CurlDownload.h:
365
        * platform/network/curl/CurlMultipartHandle.cpp:
366
        * platform/network/curl/CurlMultipartHandle.h:
367
        * platform/network/curl/CurlMultipartHandleClient.h:
368
        * platform/network/curl/CurlRequest.cpp:
369
        * platform/network/curl/CurlRequest.h:
370
        * platform/network/curl/CurlRequestClient.h:
371
        * platform/network/curl/CurlResourceHandleDelegate.cpp:
372
        * platform/network/curl/CurlResourceHandleDelegate.h:
373
        * platform/network/ios/LegacyPreviewLoaderClient.h:
374
        * platform/posix/SharedBufferPOSIX.cpp:
375
        * platform/win/PasteboardWin.cpp:
376
        * platform/win/SharedBufferWin.cpp:
377
        * testing/MockCDMFactory.cpp:
378
        * testing/MockCDMFactory.h:
379
        * testing/MockContentFilter.cpp:
380
        * testing/MockContentFilter.h:
381
        * workers/ScriptBuffer.h:
382
        * workers/WorkerFontLoadRequest.cpp:
383
        * workers/service/context/ServiceWorkerFetch.cpp:
384
        * workers/service/context/ServiceWorkerFetch.h:
385
        * workers/service/server/SWScriptStorage.cpp:
386
        * xml/XSLTProcessorLibxslt.cpp:
387
        * xml/parser/XMLDocumentParserLibxml2.cpp:
388
389
2021-11-28  Jean-Yves Avenard  <jya@apple.com>
390
391
        Add SharedBufferBuilder class
392
        https://bugs.webkit.org/show_bug.cgi?id=233442
393
        rdar://85693939
394
395
        Reviewed by NOBODY (OOPS!).
396
397
        Similar to StringBuilder, a SharedBuffer can now only be modified through
398
        a SharedBufferBuilder. A SharedBuffer becomes immutable once created.
399
400
        Fly-By: Pass SharedBuffer via const references or pointers where it's easy
401
        to do so.
402
        No change in observable behaviour; covered by existing tests.
403
404
        * Modules/cache/DOMCache.cpp:
405
        (WebCore::DOMCache::addAll):
406
        (WebCore::DOMCache::put):
407
        * Modules/fetch/FetchBodyConsumer.cpp:
408
        (WebCore::FetchBodyConsumer::clean):
409
        (WebCore::FetchBodyConsumer::resolve):
410
        (WebCore::FetchBodyConsumer::append):
411
        (WebCore::FetchBodyConsumer::setData):
412
        (WebCore::FetchBodyConsumer::takeData):
413
        (WebCore::FetchBodyConsumer::takeAsArrayBuffer):
414
        (WebCore::FetchBodyConsumer::takeAsBlob):
415
        (WebCore::FetchBodyConsumer::takeAsText):
416
        (WebCore::FetchBodyConsumer::setSource):
417
        * Modules/fetch/FetchBodyConsumer.h:
418
        (WebCore::FetchBodyConsumer::data const):
419
        (WebCore::FetchBodyConsumer::setData): Deleted.
420
        * Modules/model-element/HTMLModelElement.cpp:
421
        (WebCore::HTMLModelElement::setSourceURL):
422
        (WebCore::HTMLModelElement::dataReceived):
423
        (WebCore::HTMLModelElement::notifyFinished):
424
        * Modules/model-element/HTMLModelElement.h:
425
        * inspector/NetworkResourcesData.cpp:
426
        (WebCore::NetworkResourcesData::ResourceData::ResourceData):
427
        (WebCore::NetworkResourcesData::ResourceData::removeContent):
428
        (WebCore::NetworkResourcesData::ResourceData::hasData const):
429
        (WebCore::NetworkResourcesData::ResourceData::dataLength const):
430
        (WebCore::NetworkResourcesData::ResourceData::appendData):
431
        (WebCore::NetworkResourcesData::ResourceData::decodeDataToContent):
432
        * inspector/NetworkResourcesData.h:
433
        (WebCore::NetworkResourcesData::ResourceData::hasBufferedData const):
434
        (WebCore::NetworkResourcesData::ResourceData::hasData const): Deleted.
435
        * loader/ResourceLoader.cpp:
436
        (WebCore::ResourceLoader::releaseResources):
437
        (WebCore::ResourceLoader::setDataBufferingPolicy):
438
        (WebCore::ResourceLoader::addDataOrBuffer):
439
        (WebCore::ResourceLoader::resourceData const):
440
        (WebCore::ResourceLoader::clearResourceData):
441
        * loader/ResourceLoader.h:
442
        (WebCore::ResourceLoader::resourceData const): Deleted.
443
        * loader/SubstituteResource.h:
444
        (WebCore::SubstituteResource::data const):
445
        (WebCore::SubstituteResource::append):
446
        (WebCore::SubstituteResource::clear):
447
        (WebCore::SubstituteResource::deliver):
448
        * loader/appcache/ApplicationCacheResourceLoader.cpp:
449
        (WebCore::ApplicationCacheResourceLoader::dataReceived):
450
        * loader/appcache/ApplicationCacheStorage.cpp:
451
        (WebCore::ApplicationCacheStorage::store):
452
        * loader/archive/mhtml/MHTMLParser.cpp:
453
        (WebCore::MHTMLParser::parseNextPart):
454
        * loader/cache/CachedApplicationManifest.cpp:
455
        (WebCore::CachedApplicationManifest::finishLoading):
456
        * loader/cache/CachedApplicationManifest.h:
457
        * loader/cache/CachedCSSStyleSheet.cpp:
458
        (WebCore::CachedCSSStyleSheet::finishLoading):
459
        * loader/cache/CachedCSSStyleSheet.h:
460
        * loader/cache/CachedFont.cpp:
461
        (WebCore::CachedFont::finishLoading):
462
        * loader/cache/CachedFont.h:
463
        * loader/cache/CachedImage.cpp:
464
        (WebCore::CachedImage::updateBufferInternal):
465
        (WebCore::CachedImage::convertedDataIfNeeded const):
466
        (WebCore::CachedImage::updateBuffer):
467
        (WebCore::CachedImage::finishLoading):
468
        * loader/cache/CachedImage.h:
469
        * loader/cache/CachedRawResource.cpp:
470
        (WebCore::CachedRawResource::updateBuffer):
471
        (WebCore::CachedRawResource::finishLoading):
472
        * loader/cache/CachedRawResource.h:
473
        * loader/cache/CachedResource.cpp:
474
        (WebCore::CachedResource::updateBuffer):
475
        (WebCore::CachedResource::finishLoading):
476
        * loader/cache/CachedResource.h:
477
        * loader/cache/CachedSVGDocument.cpp:
478
        (WebCore::CachedSVGDocument::finishLoading):
479
        * loader/cache/CachedSVGDocument.h:
480
        * loader/cache/CachedScript.cpp:
481
        (WebCore::CachedScript::finishLoading):
482
        * loader/cache/CachedScript.h:
483
        * loader/cache/CachedTextTrack.cpp:
484
        (WebCore::CachedTextTrack::doUpdateBuffer):
485
        (WebCore::CachedTextTrack::updateBuffer):
486
        (WebCore::CachedTextTrack::finishLoading):
487
        * loader/cache/CachedTextTrack.h:
488
        * loader/cache/CachedXSLStyleSheet.cpp:
489
        (WebCore::CachedXSLStyleSheet::finishLoading):
490
        * loader/cache/CachedXSLStyleSheet.h:
491
        * loader/ios/LegacyPreviewLoader.h:
492
        * loader/ios/LegacyPreviewLoader.mm:
493
        (WebCore::LegacyPreviewLoader::previewConverterDidStartConverting):
494
        (WebCore::LegacyPreviewLoader::provideMainResourceForPreviewConverter):
495
        * platform/PreviewConverter.cpp:
496
        (WebCore::PreviewConverter::previewData const):
497
        (WebCore::PreviewConverter::replayToClient):
498
        * platform/PreviewConverter.h:
499
        * platform/SharedBuffer.cpp:
500
        (WebCore::SharedBuffer::append):
501
        * platform/SharedBuffer.h:
502
        (WebCore::SharedBufferBuilder::SharedBufferBuilder):
503
        (WebCore::SharedBufferBuilder::append):
504
        (WebCore::SharedBufferBuilder::operator bool const):
505
        (WebCore::SharedBufferBuilder::isNull const):
506
        (WebCore::SharedBufferBuilder::isEmpty const):
507
        (WebCore::SharedBufferBuilder::size const):
508
        (WebCore::SharedBufferBuilder::reset):
509
        (WebCore::SharedBufferBuilder::empty):
510
        (WebCore::SharedBufferBuilder::get const):
511
        (WebCore::SharedBufferBuilder::copy const):
512
        (WebCore::SharedBufferBuilder::take):
513
        (WebCore::SharedBufferBuilder::ensureBuffer):
514
        * platform/encryptedmedia/clearkey/CDMClearKey.cpp:
515
        (WebCore::extractKeyidsFromCencInitData):
516
        (WebCore::extractKeyIdFromWebMInitData):
517
        * platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.h:
518
        * platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm:
519
        (WebCore::PlatformResourceMediaLoader::dataReceived):
520
        (WebCore::WebCoreAVFResourceLoader::newDataStoredInSharedBuffer):
521
        * platform/graphics/gstreamer/eme/GStreamerEMEUtilities.h:
522
        (WebCore::InitData::InitData):
523
        (WebCore::InitData::append):
524
        (WebCore::InitData::payload const):
525
        * platform/image-decoders/jpeg/JPEGImageDecoder.cpp:
526
        (WebCore::readICCProfile):
527
        * platform/ios/PreviewConverterIOS.mm:
528
        (WebCore::PreviewConverter::PreviewConverter):
529
        * platform/mediarecorder/cocoa/MediaRecorderPrivateWriterCocoa.h:
530
        * platform/mediarecorder/cocoa/MediaRecorderPrivateWriterCocoa.mm:
531
        (WebCore::MediaRecorderPrivateWriter::~MediaRecorderPrivateWriter):
532
        (WebCore::MediaRecorderPrivateWriter::appendData):
533
        (WebCore::MediaRecorderPrivateWriter::takeData):
534
        * platform/network/cocoa/RangeResponseGenerator.mm:
535
        (WebCore::RangeResponseGenerator::Data::Data):
536
        (WebCore::RangeResponseGenerator::giveResponseToTaskIfBytesInRangeReceived):
537
        (WebCore::RangeResponseGenerator::expectedContentLengthFromData):
538
        * workers/ScriptBuffer.cpp:
539
        (WebCore::ScriptBuffer::ScriptBuffer):
540
        (WebCore::ScriptBuffer::toString const):
541
        (WebCore::ScriptBuffer::containsSingleFileMappedSegment const):
542
        (WebCore::ScriptBuffer::append):
543
        * workers/ScriptBuffer.h:
544
        (WebCore::ScriptBuffer::buffer const):
545
        (WebCore::ScriptBuffer::isolatedCopy const):
546
        (WebCore::ScriptBuffer::isEmpty const):
547
        * workers/WorkerFontLoadRequest.cpp:
548
        (WebCore::WorkerFontLoadRequest::WorkerFontLoadRequest):
549
        (WebCore::WorkerFontLoadRequest::isPending const):
550
        (WebCore::WorkerFontLoadRequest::ensureCustomFontData):
551
        (WebCore::WorkerFontLoadRequest::didReceiveData):
552
        * workers/WorkerFontLoadRequest.h:
553
        * xml/XMLHttpRequest.cpp:
554
        (WebCore::XMLHttpRequest::XMLHttpRequest):
555
        (WebCore::XMLHttpRequest::createResponseBlob):
556
        (WebCore::XMLHttpRequest::createResponseArrayBuffer):
557
        (WebCore::XMLHttpRequest::clearResponseBuffers):
558
        (WebCore::XMLHttpRequest::didReceiveData):
559
        * xml/XMLHttpRequest.h:
560
561
2021-11-25  Jean-Yves Avenard  <jya@apple.com>
562
563
        Distinguish contiguous SharedBuffer from non-contiguous one and guarantee immutability
564
        https://bugs.webkit.org/show_bug.cgi?id=233030
565
        rdar://85333814
566
567
        Reviewed by Darin Adler.
568
569
        When calling SharedBuffer::data() the underlying data was flattened,
570
        and so could be mutated while being shared. This was an undesirable
571
        behaviour.
572
        We introduce ContiguousSharedBuffer which guarantee that its content is made
573
        of contiguous data.
574
        All methods that would have mutated a SharedBuffer when being flattened are
575
        moved to ContiguousSharedBuffer.
576
577
        Area where SharedBuffers were always created with a single segment where
578
        converted to a ContiguousSharedBuffer.
579
        Previously, a SharedBuffer would have been flattened only if it needed to be
580
        and only when the data was going to be accessed; following this change
581
        the conversion is now explictly done through a call to makeContiguous.
582
        This conversion is a no-op if the SharedBuffer being converted was already
583
        a ContiguousSharedBuffer.
584
        With the nature of a SharedBuffer being shared by potentially multiple
585
        users it was necessary to limit the number of conversions being performed
586
        on demand to avoid redundancy.
587
        When the flattening could have occured, the SharedBuffer creation points were
588
        traced back and identified to make the buffer contiguous then.
589
        In the end, there's no more SharedBuffer flattening operations than there
590
        would have been before this change.
591
        There's a potential increase of temporary memory usage with the
592
        ScriptBufferSourceProvider class; bug 233511 is tracking it.
593
594
        While the change is extensive, code coverage of the modified areas is thorough
595
        which makes undetected regressions unlikely.
596
597
        In bug 233442, a SharedBuffer will be made completely immutable once created.
598
599
        No observable change.
600
        Covered by all existing tests. New API tests creatded.
601
602
        * Modules/async-clipboard/ClipboardItemBindingsDataSource.cpp:
603
        (WebCore::ClipboardItemBindingsDataSource::ClipboardItemTypeLoader::sanitizeDataIfNeeded):
604
        * Modules/async-clipboard/ios/ClipboardImageReaderIOS.mm:
605
        (WebCore::ClipboardImageReader::readBuffer):
606
        * Modules/async-clipboard/mac/ClipboardImageReaderMac.mm:
607
        (WebCore::ClipboardImageReader::readBuffer):
608
        * Modules/cache/CacheStorageConnection.cpp:
609
        (WebCore::CacheStorageConnection::computeRealBodySize):
610
        * Modules/cache/DOMCache.cpp:
611
        (WebCore::DOMCache::addAll):
612
        (WebCore::DOMCache::putWithResponseData):
613
        (WebCore::DOMCache::put):
614
        * Modules/cache/DOMCache.h:
615
        * Modules/cache/DOMCacheEngine.cpp:
616
        (WebCore::DOMCacheEngine::isolatedResponseBody):
617
        (WebCore::DOMCacheEngine::copyResponseBody):
618
        * Modules/cache/DOMCacheEngine.h:
619
        * Modules/encryptedmedia/InitDataRegistry.cpp:
620
        (WebCore::extractKeyIDsKeyids):
621
        (WebCore::sanitizeKeyids):
622
        * Modules/encryptedmedia/MediaKeyStatusMap.cpp:
623
        (WebCore::keyIdsMatch):
624
        (WebCore::MediaKeyStatusMap::Iterator::next):
625
        * Modules/fetch/FetchBody.cpp:
626
        (WebCore::FetchBody::consumeFormData):
627
        (WebCore::FetchBody::bodyAsFormData const):
628
        (WebCore::FetchBody::take):
629
        * Modules/fetch/FetchBody.h:
630
        * Modules/fetch/FetchBodyConsumer.cpp:
631
        (WebCore::FetchBodyConsumer::resolve):
632
        (WebCore::FetchBodyConsumer::takeAsText):
633
        * Modules/fetch/FetchResponse.cpp:
634
        (WebCore::FetchResponse::BodyLoader::consumeDataByChunk):
635
        (WebCore::FetchResponse::setBodyData):
636
        * Modules/fetch/FetchResponse.h:
637
        * Modules/highlight/AppHighlight.h:
638
        (WebCore::AppHighlight::encode const):
639
        * Modules/highlight/AppHighlightRangeData.cpp:
640
        (WebCore::AppHighlightRangeData::create):
641
        * Modules/indexeddb/server/IDBSerialization.cpp:
642
        (WebCore::serializeIDBKeyPath):
643
        (WebCore::serializeIDBKeyData):
644
        * Modules/indexeddb/server/IDBSerialization.h:
645
        * Modules/indexeddb/server/SQLiteIDBBackingStore.cpp:
646
        (WebCore::IDBServer::SQLiteIDBBackingStore::addExistingIndex):
647
        (WebCore::IDBServer::SQLiteIDBBackingStore::createObjectStore):
648
        (WebCore::IDBServer::SQLiteIDBBackingStore::createIndex):
649
        (WebCore::IDBServer::SQLiteIDBBackingStore::uncheckedHasIndexRecord):
650
        (WebCore::IDBServer::SQLiteIDBBackingStore::uncheckedPutIndexRecord):
651
        (WebCore::IDBServer::SQLiteIDBBackingStore::keyExistsInObjectStore):
652
        (WebCore::IDBServer::SQLiteIDBBackingStore::deleteRecord):
653
        (WebCore::IDBServer::SQLiteIDBBackingStore::addRecord):
654
        (WebCore::IDBServer::SQLiteIDBBackingStore::getRecord):
655
        (WebCore::IDBServer::SQLiteIDBBackingStore::uncheckedGetIndexRecordForOneKey):
656
        (WebCore::IDBServer::SQLiteIDBBackingStore::getCount):
657
        * Modules/indexeddb/server/SQLiteIDBCursor.cpp:
658
        (WebCore::IDBServer::SQLiteIDBCursor::bindArguments):
659
        (WebCore::IDBServer::SQLiteIDBCursor::resetAndRebindPreIndexStatementIfNecessary):
660
        * Modules/mediastream/RTCDataChannelRemoteHandler.cpp:
661
        (WebCore::RTCDataChannelRemoteHandler::readyToSend):
662
        * Modules/mediastream/libwebrtc/LibWebRTCDataChannelHandler.cpp:
663
        (WebCore::LibWebRTCDataChannelHandler::setClient):
664
        * Modules/model-element/HTMLModelElement.cpp:
665
        (WebCore::HTMLModelElement::notifyFinished):
666
        * Modules/model-element/scenekit/SceneKitModelLoaderUSD.mm:
667
        (WebCore::writeToTemporaryFile):
668
        * bindings/js/JSDOMGlobalObject.cpp:
669
        (WebCore::handleResponseOnStreamingAction):
670
        * bindings/js/ScriptBufferSourceProvider.h:
671
        * css/CSSFontFaceSource.cpp:
672
        (WebCore::CSSFontFaceSource::load):
673
        * css/CSSFontFaceSource.h:
674
        * editing/Editor.cpp:
675
        (WebCore::Editor::promisedAttachmentInfo):
676
        * editing/Editor.h:
677
        * editing/SerializedAttachmentData.h:
678
        * editing/cocoa/EditorCocoa.mm:
679
        (WebCore::archivedDataForAttributedString):
680
        (WebCore::Editor::getPasteboardTypesAndDataForAttachment):
681
        (WebCore::Editor::selectionInWebArchiveFormat):
682
        (WebCore::Editor::dataInRTFDFormat):
683
        (WebCore::Editor::dataInRTFFormat):
684
        * editing/cocoa/HTMLConverter.mm:
685
        (HTMLConverter::_addAttachmentForElement):
686
        (fileWrapperForURL):
687
        (fileWrapperForElement):
688
        * editing/cocoa/WebContentReaderCocoa.mm:
689
        (WebCore::replaceRichContentWithAttachments):
690
        (WebCore::extractMarkupAndArchive):
691
        (WebCore::sanitizeMarkupWithArchive):
692
        (WebCore::WebContentReader::readRTFD):
693
        (WebCore::WebContentMarkupReader::readRTFD):
694
        (WebCore::WebContentReader::readRTF):
695
        (WebCore::WebContentMarkupReader::readRTF):
696
        * editing/mac/EditorMac.mm:
697
        (WebCore::Editor::imageInWebArchiveFormat):
698
        (WebCore::Editor::dataSelectionForPasteboard):
699
        * html/FTPDirectoryDocument.cpp:
700
        (WebCore::createTemplateDocumentData):
701
        (WebCore::FTPDirectoryDocumentParser::loadDocumentTemplate):
702
        * inspector/NetworkResourcesData.cpp:
703
        (WebCore::NetworkResourcesData::ResourceData::decodeDataToContent):
704
        * inspector/agents/InspectorNetworkAgent.cpp:
705
        (WebCore::InspectorNetworkAgent::cachedResourceContent):
706
        * inspector/agents/InspectorPageAgent.cpp:
707
        (WebCore::InspectorPageAgent::mainResourceContent):
708
        (WebCore::InspectorPageAgent::sharedBufferContent):
709
        * loader/ContentFilter.cpp:
710
        (WebCore::ContentFilter::deliverResourceData):
711
        * loader/CrossOriginPreflightChecker.cpp:
712
        (WebCore::CrossOriginPreflightChecker::doPreflight):
713
        * loader/DocumentLoader.cpp:
714
        (WebCore::DocumentLoader::maybeCreateArchive):
715
        (WebCore::DocumentLoader::parsedArchiveData const):
716
        (WebCore::DocumentLoader::maybeFinishLoadingMultipartContent):
717
        * loader/DocumentLoader.h:
718
        * loader/DocumentThreadableLoader.cpp:
719
        (WebCore::DocumentThreadableLoader::loadRequest):
720
        * loader/EmptyClients.cpp:
721
        * loader/FrameLoader.cpp:
722
        (WebCore::FrameLoader::loadResourceSynchronously):
723
        * loader/FrameLoader.h:
724
        * loader/ResourceLoader.cpp:
725
        (WebCore::ResourceLoader::didReceiveDataOrBuffer):
726
        * loader/SubresourceLoader.cpp:
727
        (WebCore::SubresourceLoader::didReceiveDataOrBuffer):
728
        * loader/appcache/ApplicationCacheGroup.cpp:
729
        (WebCore::ApplicationCacheGroup::didFinishLoadingManifest):
730
        * loader/appcache/ApplicationCacheHost.cpp:
731
        (WebCore::bufferFromResource):
732
        (WebCore::ApplicationCacheHost::maybeLoadSynchronously):
733
        (WebCore::ApplicationCacheHost::maybeLoadFallbackSynchronously):
734
        * loader/appcache/ApplicationCacheHost.h:
735
        * loader/appcache/ApplicationCacheResource.cpp:
736
        (WebCore::ApplicationCacheResource::deliver):
737
        * loader/appcache/ApplicationCacheStorage.cpp:
738
        (WebCore::ApplicationCacheStorage::store):
739
        (WebCore::ApplicationCacheStorage::loadCache):
740
        * loader/archive/cf/LegacyWebArchive.cpp:
741
        (WebCore::LegacyWebArchive::createPropertyListRepresentation):
742
        (WebCore::LegacyWebArchive::createResource):
743
        (WebCore::LegacyWebArchive::create):
744
        (WebCore::LegacyWebArchive::extract):
745
        (WebCore::LegacyWebArchive::createFromSelection):
746
        * loader/archive/mhtml/MHTMLParser.cpp:
747
        (WebCore::MHTMLParser::parseNextPart):
748
        * loader/cache/CachedApplicationManifest.cpp:
749
        (WebCore::CachedApplicationManifest::finishLoading):
750
        * loader/cache/CachedCSSStyleSheet.cpp:
751
        (WebCore::CachedCSSStyleSheet::sheetText const):
752
        (WebCore::CachedCSSStyleSheet::finishLoading):
753
        * loader/cache/CachedFont.cpp:
754
        (WebCore::CachedFont::finishLoading):
755
        (WebCore::CachedFont::ensureCustomFontData):
756
        (WebCore::CachedFont::createCustomFontData):
757
        (WebCore::CachedFont::checkNotify):
758
        * loader/cache/CachedFont.h:
759
        * loader/cache/CachedImage.cpp:
760
        (WebCore::CachedImage::updateBufferInternal):
761
        (WebCore::CachedImage::convertedDataIfNeeded const):
762
        * loader/cache/CachedImage.h:
763
        * loader/cache/CachedRawResource.cpp:
764
        (WebCore::CachedRawResource::updateBuffer):
765
        (WebCore::CachedRawResource::finishLoading):
766
        * loader/cache/CachedResource.cpp:
767
        (WebCore::CachedResource::tryReplaceEncodedData):
768
        * loader/cache/CachedResource.h:
769
        (WebCore::CachedResource::resourceBuffer const):
770
        * loader/cache/CachedSVGDocument.cpp:
771
        (WebCore::CachedSVGDocument::finishLoading):
772
        * loader/cache/CachedSVGFont.cpp:
773
        (WebCore::CachedSVGFont::ensureCustomFontData):
774
        * loader/cache/CachedSVGFont.h:
775
        * loader/cache/CachedScript.cpp:
776
        (WebCore::CachedScript::finishLoading):
777
        * loader/cache/CachedTextTrack.cpp:
778
        (WebCore::CachedTextTrack::doUpdateBuffer):
779
        * loader/cache/CachedXSLStyleSheet.cpp:
780
        (WebCore::CachedXSLStyleSheet::finishLoading):
781
        * loader/cocoa/DiskCacheMonitorCocoa.h:
782
        * loader/cocoa/DiskCacheMonitorCocoa.mm:
783
        (WebCore::DiskCacheMonitor::tryGetFileBackedSharedBufferFromCFURLCachedResponse):
784
        (WebCore::DiskCacheMonitor::resourceBecameFileBacked):
785
        * page/EditorClient.h:
786
        * page/Page.cpp:
787
        (WebCore::Page::userStyleSheet const):
788
        * page/PageSerializer.cpp:
789
        (WebCore::PageSerializer::serializeFrame):
790
        (WebCore::PageSerializer::serializeCSSStyleSheet):
791
        (WebCore::PageSerializer::addImageToResources):
792
        * page/PageSerializer.h:
793
        * page/ShareData.h:
794
        * page/ShareDataReader.cpp:
795
        (WebCore::ShareDataReader::ShareDataReader):
796
        (WebCore::ShareDataReader::didFinishLoading):
797
        * platform/KeyedCoding.h:
798
        * platform/Pasteboard.h:
799
        * platform/PasteboardCustomData.cpp:
800
        (WebCore::PasteboardCustomData::createSharedBuffer const):
801
        (WebCore::PasteboardCustomData::fromSharedBuffer):
802
        * platform/PasteboardCustomData.h:
803
        * platform/PasteboardStrategy.h:
804
        * platform/PasteboardWriterData.h:
805
        * platform/PlatformPasteboard.h:
806
        * platform/PromisedAttachmentInfo.h:
807
        * platform/SharedBuffer.cpp:
808
        (WebCore::SharedBuffer::SharedBuffer):
809
        (WebCore::SharedBuffer::makeContiguous const):
810
        (WebCore::SharedBuffer::size const):
811
        (WebCore::SharedBuffer::isEmpty const):
812
        (WebCore::SharedBuffer::isContiguous const):
813
        (WebCore::SharedBuffer::append):
814
        (WebCore::SharedBuffer::copy const):
815
        (WebCore::SharedBuffer::hasOneSegment const):
816
        (WebCore::ContiguousSharedBuffer::ContiguousSharedBuffer):
817
        (WebCore::ContiguousSharedBuffer::createWithContentsOfFile):
818
        (WebCore::ContiguousSharedBuffer::data const):
819
        (WebCore::ContiguousSharedBuffer::dataAsCharPtr const):
820
        (WebCore::DataSegment::data const):
821
        (WebCore::DataSegment::containsMappedFileData const):
822
        (WebCore::ContiguousSharedBuffer::decoder const):
823
        (WebCore::DataSegment::size const):
824
        (WebCore::SharedBufferDataView::SharedBufferDataView):
825
        (WebCore::SharedBufferDataView::dataAsCharPtr const):
826
        (WebCore::SharedBufferDataView::createSharedBuffer const):
827
        (WebCore::utf8Buffer):
828
        * platform/SharedBuffer.h:
829
        (WebCore::DataSegment::create):
830
        (WebCore::DataSegment::DataSegment):
831
        (WebCore::SharedBuffer::create):
832
        (WebCore::ContiguousSharedBuffer::create):
833
        * platform/audio/cocoa/MediaSessionManagerCocoa.mm:
834
        (WebCore::MediaSessionManagerCocoa::setNowPlayingInfo):
835
        * platform/cf/KeyedEncoderCF.cpp:
836
        (WebCore::KeyedEncoderCF::finishEncoding):
837
        * platform/cf/KeyedEncoderCF.h:
838
        * platform/cf/SharedBufferCF.cpp:
839
        (WebCore::ContiguousSharedBuffer::createCFData const):
840
        (WebCore::SharedBuffer::append):
841
        * platform/cocoa/PasteboardCocoa.mm:
842
        (WebCore::convertTIFFToPNG):
843
        (WebCore::Pasteboard::readBufferForTypeWithSecurityCheck):
844
        * platform/cocoa/SharedBufferCocoa.mm:
845
        (-[WebCoreSharedBufferData initWithDataSegment:position:size:]):
846
        (WebCore::ContiguousSharedBuffer::createNSData const):
847
        (WebCore::ContiguousSharedBuffer::createCFData const):
848
        (WebCore::ContiguousSharedBuffer::createFromReadingFile):
849
        (WebCore::DataSegment::createNSData const):
850
        * platform/encryptedmedia/CDMUtilities.cpp:
851
        (WebCore::CDMUtilities::parseJSONObject):
852
        * platform/encryptedmedia/clearkey/CDMClearKey.cpp:
853
        (WebCore::extractKeyidsLocationFromCencInitData):
854
        (WebCore::extractKeyidsFromCencInitData):
855
        (WebCore::extractKeyIdFromWebMInitData):
856
        * platform/generic/KeyedEncoderGeneric.cpp:
857
        (WebCore::KeyedEncoderGeneric::finishEncoding):
858
        * platform/generic/KeyedEncoderGeneric.h:
859
        * platform/glib/KeyedEncoderGlib.cpp:
860
        (WebCore::KeyedEncoderGlib::finishEncoding):
861
        * platform/glib/KeyedEncoderGlib.h:
862
        * platform/glib/SharedBufferGlib.cpp:
863
        (WebCore::ContiguousSharedBuffer::createGBytes const):
864
        (WebCore::ContiguousSharedBuffer::createFromReadingFile):
865
        * platform/graphics/Font.cpp:
866
        (WebCore::Font::create):
867
        * platform/graphics/Font.h:
868
        * platform/graphics/FontPlatformData.h:
869
        * platform/graphics/Model.cpp:
870
        (WebCore::Model::create):
871
        (WebCore::Model::Model):
872
        * platform/graphics/Model.h:
873
        (WebCore::Model::encode const):
874
        (WebCore::Model::decode):
875
        * platform/graphics/WOFFFileFormat.cpp:
876
        (WebCore::readUInt32):
877
        (WebCore::readUInt16):
878
        (WebCore::isWOFF):
879
        (WebCore::convertWOFFToSfnt):
880
        (WebCore::convertWOFFToSfntIfNecessary):
881
        * platform/graphics/WOFFFileFormat.h:
882
        * platform/graphics/avfoundation/CDMFairPlayStreaming.cpp:
883
        (WebCore::extractSinfData):
884
        * platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm:
885
        (WebCore::parseJSONValue):
886
        (WebCore::CDMInstanceSessionFairPlayStreamingAVFObjC::requestLicense):
887
        (WebCore::CDMInstanceSessionFairPlayStreamingAVFObjC::updateLicense):
888
        (WebCore::CDMInstanceSessionFairPlayStreamingAVFObjC::loadSession):
889
        (WebCore::CDMInstanceSessionFairPlayStreamingAVFObjC::removeSessionData):
890
        (WebCore::CDMInstanceSessionFairPlayStreamingAVFObjC::didProvideRequest):
891
        (WebCore::CDMInstanceSessionFairPlayStreamingAVFObjC::didProvideRequests):
892
        (WebCore::CDMInstanceSessionFairPlayStreamingAVFObjC::didProvideRenewingRequest):
893
        * platform/graphics/avfoundation/objc/ImageDecoderAVFObjC.mm:
894
        (WebCore::ImageDecoderAVFObjC::ImageDecoderAVFObjC):
895
        (WebCore::ImageDecoderAVFObjC::setData):
896
        * platform/graphics/avfoundation/objc/SourceBufferParserAVFObjC.mm:
897
        (WebCore::SourceBufferParserAVFObjC::appendData):
898
        * platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm:
899
        (WebCore::PlatformResourceMediaLoader::dataReceived):
900
        (WebCore::DataURLResourceMediaLoader::DataURLResourceMediaLoader):
901
        * platform/graphics/cairo/FontCustomPlatformData.h:
902
        * platform/graphics/cg/ImageDecoderCG.cpp:
903
        (WebCore::sharedBufferGetBytesAtPosition):
904
        (WebCore::ImageDecoderCG::ImageDecoderCG):
905
        (WebCore::ImageDecoderCG::setData):
906
        * platform/graphics/cg/PDFDocumentImage.cpp:
907
        (WebCore::PDFDocumentImage::createPDFDocument):
908
        * platform/graphics/cocoa/FontPlatformDataCocoa.mm:
909
        (WebCore::FontPlatformData::platformOpenTypeTable const):
910
        * platform/graphics/cocoa/SourceBufferParserWebM.cpp:
911
        * platform/graphics/coretext/FontPlatformDataCoreText.cpp:
912
        (WebCore::FontPlatformData::openTypeTable const):
913
        * platform/graphics/freetype/FontCustomPlatformDataFreeType.cpp:
914
        (WebCore::createFontCustomPlatformData):
915
        * platform/graphics/freetype/FontPlatformDataFreeType.cpp:
916
        (WebCore::FontPlatformData::openTypeTable const):
917
        * platform/graphics/gstreamer/GStreamerCommon.cpp:
918
        (WebCore::GstMappedOwnedBuffer::createSharedBuffer):
919
        * platform/graphics/gstreamer/GStreamerCommon.h:
920
        * platform/graphics/gstreamer/ImageDecoderGStreamer.cpp:
921
        (WebCore::ImageDecoderGStreamer::pushEncodedData):
922
        * platform/graphics/gstreamer/MediaPlayerPrivateGStreamer.cpp:
923
        (WebCore::MediaPlayerPrivateGStreamer::initializationDataEncountered):
924
        * platform/graphics/gstreamer/eme/GStreamerEMEUtilities.cpp:
925
        (WebCore::markupText):
926
        (WebCore::InitData::extractCencIfNeeded):
927
        * platform/graphics/gstreamer/eme/GStreamerEMEUtilities.h:
928
        (WebCore::InitData::InitData):
929
        * platform/graphics/mac/FontCustomPlatformData.cpp:
930
        (WebCore::createFontCustomPlatformData):
931
        * platform/graphics/mac/FontCustomPlatformData.h:
932
        * platform/graphics/mac/PDFDocumentImageMac.mm:
933
        (WebCore::PDFDocumentImage::createPDFDocument):
934
        * platform/graphics/opentype/OpenTypeMathData.cpp:
935
        (WebCore::OpenType::MathItalicsCorrectionInfo::getItalicCorrection const):
936
        (WebCore::OpenType::MathGlyphInfo::mathItalicsCorrectionInfo const):
937
        (WebCore::OpenType::GlyphAssembly::getAssemblyParts const):
938
        (WebCore::OpenType::MathGlyphConstruction::getSizeVariants const):
939
        (WebCore::OpenType::MathGlyphConstruction::getAssemblyParts const):
940
        (WebCore::OpenType::MathVariants::mathGlyphConstruction const):
941
        (WebCore::OpenType::MATHTable::mathConstants const):
942
        (WebCore::OpenType::MATHTable::mathGlyphInfo const):
943
        (WebCore::OpenType::MATHTable::mathVariants const):
944
        * platform/graphics/opentype/OpenTypeMathData.h:
945
        * platform/graphics/opentype/OpenTypeTypes.h:
946
        (WebCore::OpenType::validateTable):
947
        (WebCore::OpenType::TableBase::isValidEnd):
948
        (WebCore::OpenType::TableBase::validatePtr):
949
        (WebCore::OpenType::TableBase::validateOffset const):
950
        (WebCore::OpenType::TableWithCoverage::getCoverageIndex const):
951
        * platform/graphics/opentype/OpenTypeUtilities.cpp:
952
        (WebCore::renameFont):
953
        (WebCore::renameAndActivateFont):
954
        * platform/graphics/opentype/OpenTypeUtilities.h:
955
        * platform/graphics/opentype/OpenTypeVerticalData.cpp:
956
        (WebCore::OpenType::SubstitutionSubTable::coverage const):
957
        (WebCore::OpenType::LookupTable::getSubstitutions const):
958
        (WebCore::OpenType::LookupList::lookup const):
959
        (WebCore::OpenType::FeatureTable::getGlyphSubstitutions const):
960
        (WebCore::OpenType::FeatureList::feature const):
961
        (WebCore::OpenType::FeatureList::findFeature const):
962
        (WebCore::OpenType::LangSysTable::feature const):
963
        (WebCore::OpenType::ScriptTable::defaultLangSys const):
964
        (WebCore::OpenType::ScriptList::script const):
965
        (WebCore::OpenType::ScriptList::defaultScript const):
966
        (WebCore::OpenType::ScriptList::defaultLangSys const):
967
        (WebCore::OpenType::GSUBTable::scriptList const):
968
        (WebCore::OpenType::GSUBTable::featureList const):
969
        (WebCore::OpenType::GSUBTable::lookupList const):
970
        (WebCore::OpenType::GSUBTable::defaultLangSys const):
971
        (WebCore::OpenType::GSUBTable::feature const):
972
        (WebCore::OpenType::GSUBTable::getVerticalGlyphSubstitutions const):
973
        (WebCore::loadHmtxTable):
974
        (WebCore::OpenTypeVerticalData::loadMetrics):
975
        (WebCore::OpenTypeVerticalData::loadVerticalGlyphSubstitutions):
976
        * platform/graphics/win/FontCustomPlatformData.cpp:
977
        (WebCore::createFontCustomPlatformData):
978
        * platform/graphics/win/FontCustomPlatformData.h:
979
        * platform/graphics/win/FontCustomPlatformDataCairo.cpp:
980
        (WebCore::createFontCustomPlatformData):
981
        * platform/graphics/win/FontPlatformDataCairoWin.cpp:
982
        (WebCore::FontPlatformData::openTypeTable const):
983
        * platform/graphics/win/FontPlatformDataWin.cpp:
984
        (WebCore::FontPlatformData::platformOpenTypeTable const):
985
        * platform/gtk/SelectionData.h:
986
        (WebCore::SelectionData::setCustomData):
987
        (WebCore::SelectionData::customData const):
988
        * platform/image-decoders/ScalableImageDecoder.h:
989
        * platform/image-decoders/jpeg/JPEGImageDecoder.cpp:
990
        (WebCore::readICCProfile):
991
        (WebCore::JPEGImageDecoder::setICCProfile):
992
        * platform/image-decoders/jpeg/JPEGImageDecoder.h:
993
        * platform/ios/PlatformPasteboardIOS.mm:
994
        (WebCore::PlatformPasteboard::bufferForType):
995
        (WebCore::PlatformPasteboard::write):
996
        (WebCore::PlatformPasteboard::typesSafeForDOMToReadAndWrite const):
997
        (WebCore::createItemProviderRegistrationList):
998
        (WebCore::PlatformPasteboard::readBuffer const):
999
        * platform/mac/PasteboardMac.mm:
1000
        (WebCore::fileWrapper):
1001
        (WebCore::readBufferAtPreferredItemIndex):
1002
        (WebCore::Pasteboard::read):
1003
        * platform/mac/PasteboardWriter.mm:
1004
        (WebCore::createPasteboardWriter):
1005
        * platform/mac/PlatformPasteboardMac.mm:
1006
        (WebCore::PlatformPasteboard::bufferForType):
1007
        (WebCore::PlatformPasteboard::typesSafeForDOMToReadAndWrite const):
1008
        (WebCore::PlatformPasteboard::write):
1009
        (WebCore::PlatformPasteboard::setBufferForType):
1010
        (WebCore::PlatformPasteboard::readBuffer const):
1011
        (WebCore::createPasteboardItem):
1012
        * platform/network/FormData.cpp:
1013
        (WebCore::FormData::asSharedBuffer const):
1014
        * platform/network/FormData.h:
1015
        * platform/network/ResourceHandleClient.cpp:
1016
        (WebCore::ResourceHandleClient::didReceiveBuffer):
1017
        * platform/network/cocoa/WebCoreNSURLSession.mm:
1018
        (-[WebCoreNSURLSessionDataTask resource:receivedData:]):
1019
        * platform/network/curl/CurlMultipartHandle.cpp:
1020
        (WebCore::CurlMultipartHandle::didReceiveData):
1021
        (WebCore::CurlMultipartHandle::didComplete):
1022
        (WebCore::CurlMultipartHandle::processContent):
1023
        * platform/network/curl/CurlRequest.cpp:
1024
        (WebCore::CurlRequest::writeDataToDownloadFileIfEnabled):
1025
        * platform/network/curl/CurlResourceHandleDelegate.cpp:
1026
        (WebCore::CurlResourceHandleDelegate::curlDidReceiveBuffer):
1027
        * platform/win/PasteboardWin.cpp:
1028
        (WebCore::createGlobalImageFileContent):
1029
        (WebCore::createGlobalHDropContent):
1030
        * platform/win/SharedBufferWin.cpp:
1031
        (WebCore::ContiguousSharedBuffer::createFromReadingFile):
1032
        * testing/MockCDMFactory.cpp:
1033
        (WebCore::MockCDM::sanitizeResponse const):
1034
        (WebCore::MockCDMInstance::setServerCertificate):
1035
        (WebCore::MockCDMInstanceSession::updateLicense):
1036
        * workers/WorkerFontLoadRequest.cpp:
1037
        (WebCore::WorkerFontLoadRequest::ensureCustomFontData):
1038
        * workers/service/context/ServiceWorkerFetch.cpp:
1039
        (WebCore::ServiceWorkerFetch::processResponse):
1040
        * workers/service/server/SWScriptStorage.cpp:
1041
        (WebCore::SWScriptStorage::retrieve):
1042
        * xml/XSLTProcessorLibxslt.cpp:
1043
        (WebCore::docLoaderFunc):
1044
        * xml/parser/XMLDocumentParserLibxml2.cpp:
1045
        (WebCore::openFunc):
1046
1
2021-12-06  Antti Koivisto  <antti@apple.com>
1047
2021-12-06  Antti Koivisto  <antti@apple.com>
2
1048
3
        [LFC][Integration] Use end bits in text box iterator
1049
        [LFC][Integration] Use end bits in text box iterator
- a/Source/WebCore/Modules/async-clipboard/ClipboardImageReader.cpp -1 / +1 lines
Lines 33-39 namespace WebCore { a/Source/WebCore/Modules/async-clipboard/ClipboardImageReader.cpp_sec1
33
33
34
#if !PLATFORM(COCOA)
34
#if !PLATFORM(COCOA)
35
35
36
void ClipboardImageReader::readBuffer(const String&, const String&, Ref<SharedBuffer>&&)
36
void ClipboardImageReader::readBuffer(const String&, const String&, Ref<FragmentedSharedBuffer>&&)
37
{
37
{
38
    notImplemented();
38
    notImplemented();
39
}
39
}
- a/Source/WebCore/Modules/async-clipboard/ClipboardImageReader.h -2 / +2 lines
Lines 31-37 a/Source/WebCore/Modules/async-clipboard/ClipboardImageReader.h_sec1
31
namespace WebCore {
31
namespace WebCore {
32
32
33
class Document;
33
class Document;
34
class SharedBuffer;
34
class FragmentedSharedBuffer;
35
35
36
struct ClipboardImageReader : PasteboardFileReader {
36
struct ClipboardImageReader : PasteboardFileReader {
37
    ClipboardImageReader(Document* document, const String& mimeType)
37
    ClipboardImageReader(Document* document, const String& mimeType)
Lines 47-53 private: a/Source/WebCore/Modules/async-clipboard/ClipboardImageReader.h_sec2
47
    void readFilename(const String&) final { ASSERT_NOT_REACHED(); }
47
    void readFilename(const String&) final { ASSERT_NOT_REACHED(); }
48
48
49
    bool shouldReadBuffer(const String&) const final;
49
    bool shouldReadBuffer(const String&) const final;
50
    void readBuffer(const String& filename, const String& type, Ref<SharedBuffer>&&) final;
50
    void readBuffer(const String& filename, const String& type, Ref<FragmentedSharedBuffer>&&) final;
51
51
52
    RefPtr<Document> m_document;
52
    RefPtr<Document> m_document;
53
    String m_mimeType;
53
    String m_mimeType;
- a/Source/WebCore/Modules/async-clipboard/ClipboardItemBindingsDataSource.cpp -8 / +8 lines
Lines 216-223 void ClipboardItemBindingsDataSource::invokeCompletionHandler() a/Source/WebCore/Modules/async-clipboard/ClipboardItemBindingsDataSource.cpp_sec1
216
        auto& data = itemTypeLoader->data();
216
        auto& data = itemTypeLoader->data();
217
        if (std::holds_alternative<String>(data) && !!std::get<String>(data))
217
        if (std::holds_alternative<String>(data) && !!std::get<String>(data))
218
            customData.writeString(type, std::get<String>(data));
218
            customData.writeString(type, std::get<String>(data));
219
        else if (std::holds_alternative<Ref<SharedBuffer>>(data))
219
        else if (std::holds_alternative<Ref<FragmentedSharedBuffer>>(data))
220
            customData.writeData(type, std::get<Ref<SharedBuffer>>(data).copyRef());
220
            customData.writeData(type, std::get<Ref<FragmentedSharedBuffer>>(data).copyRef());
221
        else {
221
        else {
222
            completionHandler(std::nullopt);
222
            completionHandler(std::nullopt);
223
            return;
223
            return;
Lines 265-273 void ClipboardItemBindingsDataSource::ClipboardItemTypeLoader::sanitizeDataIfNee a/Source/WebCore/Modules/async-clipboard/ClipboardItemBindingsDataSource.cpp_sec2
265
{
265
{
266
    if (m_type == "text/html"_s) {
266
    if (m_type == "text/html"_s) {
267
        String markupToSanitize;
267
        String markupToSanitize;
268
        if (std::holds_alternative<Ref<SharedBuffer>>(m_data)) {
268
        if (std::holds_alternative<Ref<FragmentedSharedBuffer>>(m_data)) {
269
            auto& buffer = std::get<Ref<SharedBuffer>>(m_data);
269
            auto& buffer = std::get<Ref<FragmentedSharedBuffer>>(m_data);
270
            markupToSanitize = String::fromUTF8(buffer->data(), buffer->size());
270
            markupToSanitize = String::fromUTF8(buffer->makeContiguous()->data(), buffer->size());
271
        } else if (std::holds_alternative<String>(m_data))
271
        } else if (std::holds_alternative<String>(m_data))
272
            markupToSanitize = std::get<String>(m_data);
272
            markupToSanitize = std::get<String>(m_data);
273
273
Lines 278-286 void ClipboardItemBindingsDataSource::ClipboardItemTypeLoader::sanitizeDataIfNee a/Source/WebCore/Modules/async-clipboard/ClipboardItemBindingsDataSource.cpp_sec3
278
    }
278
    }
279
279
280
    if (m_type == "image/png"_s) {
280
    if (m_type == "image/png"_s) {
281
        RefPtr<SharedBuffer> bufferToSanitize;
281
        RefPtr<FragmentedSharedBuffer> bufferToSanitize;
282
        if (std::holds_alternative<Ref<SharedBuffer>>(m_data))
282
        if (std::holds_alternative<Ref<FragmentedSharedBuffer>>(m_data))
283
            bufferToSanitize = std::get<Ref<SharedBuffer>>(m_data).ptr();
283
            bufferToSanitize = std::get<Ref<FragmentedSharedBuffer>>(m_data).ptr();
284
        else if (std::holds_alternative<String>(m_data))
284
        else if (std::holds_alternative<String>(m_data))
285
            bufferToSanitize = utf8Buffer(std::get<String>(m_data));
285
            bufferToSanitize = utf8Buffer(std::get<String>(m_data));
286
286
- a/Source/WebCore/Modules/async-clipboard/ClipboardItemBindingsDataSource.h -2 / +2 lines
Lines 38-44 class DOMPromise; a/Source/WebCore/Modules/async-clipboard/ClipboardItemBindingsDataSource.h_sec1
38
class FileReaderLoader;
38
class FileReaderLoader;
39
class PasteboardCustomData;
39
class PasteboardCustomData;
40
class ScriptExecutionContext;
40
class ScriptExecutionContext;
41
class SharedBuffer;
41
class FragmentedSharedBuffer;
42
42
43
class ClipboardItemBindingsDataSource : public ClipboardItemDataSource {
43
class ClipboardItemBindingsDataSource : public ClipboardItemDataSource {
44
    WTF_MAKE_FAST_ALLOCATED;
44
    WTF_MAKE_FAST_ALLOCATED;
Lines 53-59 private: a/Source/WebCore/Modules/async-clipboard/ClipboardItemBindingsDataSource.h_sec2
53
53
54
    void invokeCompletionHandler();
54
    void invokeCompletionHandler();
55
55
56
    using BufferOrString = std::variant<String, Ref<SharedBuffer>>;
56
    using BufferOrString = std::variant<String, Ref<FragmentedSharedBuffer>>;
57
    class ClipboardItemTypeLoader : public FileReaderLoaderClient, public RefCounted<ClipboardItemTypeLoader> {
57
    class ClipboardItemTypeLoader : public FileReaderLoaderClient, public RefCounted<ClipboardItemTypeLoader> {
58
    public:
58
    public:
59
        static Ref<ClipboardItemTypeLoader> create(const String& type, CompletionHandler<void()>&& completionHandler)
59
        static Ref<ClipboardItemTypeLoader> create(const String& type, CompletionHandler<void()>&& completionHandler)
- a/Source/WebCore/Modules/async-clipboard/ios/ClipboardImageReaderIOS.mm -2 / +2 lines
Lines 34-43 a/Source/WebCore/Modules/async-clipboard/ios/ClipboardImageReaderIOS.mm_sec1
34
34
35
namespace WebCore {
35
namespace WebCore {
36
36
37
void ClipboardImageReader::readBuffer(const String&, const String&, Ref<SharedBuffer>&& buffer)
37
void ClipboardImageReader::readBuffer(const String&, const String&, Ref<FragmentedSharedBuffer>&& buffer)
38
{
38
{
39
    if (m_mimeType == "image/png") {
39
    if (m_mimeType == "image/png") {
40
        auto image = adoptNS([PAL::allocUIImageInstance() initWithData:buffer->createNSData().get()]);
40
        auto image = adoptNS([PAL::allocUIImageInstance() initWithData:buffer->makeContiguous()->createNSData().get()]);
41
        if (auto nsData = UIImagePNGRepresentation(image.get()))
41
        if (auto nsData = UIImagePNGRepresentation(image.get()))
42
            m_result = Blob::create(m_document.get(), Vector { static_cast<const uint8_t*>(nsData.bytes), nsData.length }, m_mimeType);
42
            m_result = Blob::create(m_document.get(), Vector { static_cast<const uint8_t*>(nsData.bytes), nsData.length }, m_mimeType);
43
    }
43
    }
- a/Source/WebCore/Modules/async-clipboard/mac/ClipboardImageReaderMac.mm -2 / +2 lines
Lines 33-42 a/Source/WebCore/Modules/async-clipboard/mac/ClipboardImageReaderMac.mm_sec1
33
33
34
namespace WebCore {
34
namespace WebCore {
35
35
36
void ClipboardImageReader::readBuffer(const String&, const String&, Ref<SharedBuffer>&& buffer)
36
void ClipboardImageReader::readBuffer(const String&, const String&, Ref<FragmentedSharedBuffer>&& buffer)
37
{
37
{
38
    if (m_mimeType == "image/png") {
38
    if (m_mimeType == "image/png") {
39
        auto image = adoptNS([[NSImage alloc] initWithData:buffer->createNSData().get()]);
39
        auto image = adoptNS([[NSImage alloc] initWithData:buffer->makeContiguous()->createNSData().get()]);
40
        if (auto cgImage = [image CGImageForProposedRect:nil context:nil hints:nil]) {
40
        if (auto cgImage = [image CGImageForProposedRect:nil context:nil hints:nil]) {
41
            auto representation = adoptNS([[NSBitmapImageRep alloc] initWithCGImage:cgImage]);
41
            auto representation = adoptNS([[NSBitmapImageRep alloc] initWithCGImage:cgImage]);
42
            NSData* nsData = [representation representationUsingType:NSBitmapImageFileTypePNG properties:@{ }];
42
            NSData* nsData = [representation representationUsingType:NSBitmapImageFileTypePNG properties:@{ }];
- a/Source/WebCore/Modules/cache/DOMCache.cpp -7 / +7 lines
Lines 289-295 void DOMCache::addAll(Vector<RequestInfo>&& infos, DOMPromiseDeferred<void>&& pr a/Source/WebCore/Modules/cache/DOMCache.cpp_sec1
289
            }
289
            }
290
            size_t recordPosition = taskHandler->addRecord(toConnectionRecord(request.get(), response, nullptr));
290
            size_t recordPosition = taskHandler->addRecord(toConnectionRecord(request.get(), response, nullptr));
291
291
292
            response.consumeBodyReceivedByChunk([taskHandler = WTFMove(taskHandler), recordPosition, data = SharedBuffer::create(), response = Ref { response }] (auto&& result) mutable {
292
            response.consumeBodyReceivedByChunk([taskHandler = WTFMove(taskHandler), recordPosition, data = SharedBufferBuilder(), response = Ref { response }] (auto&& result) mutable {
293
                if (taskHandler->isDone())
293
                if (taskHandler->isDone())
294
                    return;
294
                    return;
295
295
Lines 299-307 void DOMCache::addAll(Vector<RequestInfo>&& infos, DOMPromiseDeferred<void>&& pr a/Source/WebCore/Modules/cache/DOMCache.cpp_sec2
299
                }
299
                }
300
300
301
                if (auto* chunk = result.returnValue())
301
                if (auto* chunk = result.returnValue())
302
                    data->append(chunk->data(), chunk->size());
302
                    data.append(chunk->data(), chunk->size());
303
                else
303
                else
304
                    taskHandler->addResponseBody(recordPosition, response, WTFMove(data));
304
                    taskHandler->addResponseBody(recordPosition, response, data.take()->makeContiguous());
305
            });
305
            });
306
        }, cachedResourceRequestInitiators().fetch);
306
        }, cachedResourceRequestInitiators().fetch);
307
    }
307
    }
Lines 318-324 void DOMCache::putWithResponseData(DOMPromiseDeferred<void>&& promise, Ref<Fetch a/Source/WebCore/Modules/cache/DOMCache.cpp_sec3
318
318
319
    DOMCacheEngine::ResponseBody body;
319
    DOMCacheEngine::ResponseBody body;
320
    if (auto buffer = responseBody.releaseReturnValue())
320
    if (auto buffer = responseBody.releaseReturnValue())
321
        body = buffer.releaseNonNull();
321
        body = buffer->makeContiguous();
322
    batchPutOperation(request.get(), response.get(), WTFMove(body), [this, protectedThis = Ref { *this }, promise = WTFMove(promise)](ExceptionOr<void>&& result) mutable {
322
    batchPutOperation(request.get(), response.get(), WTFMove(body), [this, protectedThis = Ref { *this }, promise = WTFMove(promise)](ExceptionOr<void>&& result) mutable {
323
        queueTaskKeepingObjectAlive(*this, TaskSource::DOMManipulation, [promise = WTFMove(promise), result = WTFMove(result)]() mutable {
323
        queueTaskKeepingObjectAlive(*this, TaskSource::DOMManipulation, [promise = WTFMove(promise), result = WTFMove(result)]() mutable {
324
            promise.settle(WTFMove(result));
324
            promise.settle(WTFMove(result));
Lines 375-381 void DOMCache::put(RequestInfo&& info, Ref<FetchResponse>&& response, DOMPromise a/Source/WebCore/Modules/cache/DOMCache.cpp_sec4
375
375
376
    if (response->isBodyReceivedByChunk()) {
376
    if (response->isBodyReceivedByChunk()) {
377
        auto& responseRef = response.get();
377
        auto& responseRef = response.get();
378
        responseRef.consumeBodyReceivedByChunk([promise = WTFMove(promise), request = WTFMove(request), response = WTFMove(response), data = SharedBuffer::create(), pendingActivity = makePendingActivity(*this), this](auto&& result) mutable {
378
        responseRef.consumeBodyReceivedByChunk([promise = WTFMove(promise), request = WTFMove(request), response = WTFMove(response), data = SharedBufferBuilder(), pendingActivity = makePendingActivity(*this), this](auto&& result) mutable {
379
379
380
            if (result.hasException()) {
380
            if (result.hasException()) {
381
                this->putWithResponseData(WTFMove(promise), WTFMove(request), WTFMove(response), result.releaseException().isolatedCopy());
381
                this->putWithResponseData(WTFMove(promise), WTFMove(request), WTFMove(response), result.releaseException().isolatedCopy());
Lines 383-391 void DOMCache::put(RequestInfo&& info, Ref<FetchResponse>&& response, DOMPromise a/Source/WebCore/Modules/cache/DOMCache.cpp_sec5
383
            }
383
            }
384
384
385
            if (auto* chunk = result.returnValue())
385
            if (auto* chunk = result.returnValue())
386
                data->append(chunk->data(), chunk->size());
386
                data.append(chunk->data(), chunk->size());
387
            else
387
            else
388
                this->putWithResponseData(WTFMove(promise), WTFMove(request), WTFMove(response), RefPtr<SharedBuffer> { WTFMove(data) });
388
                this->putWithResponseData(WTFMove(promise), WTFMove(request), WTFMove(response), RefPtr<SharedBuffer> { data.take()->makeContiguous() });
389
        });
389
        });
390
        return;
390
        return;
391
    }
391
    }
- a/Source/WebCore/Modules/cache/DOMCacheEngine.cpp -1 / +1 lines
Lines 132-138 ResponseBody isolatedResponseBody(const ResponseBody& body) a/Source/WebCore/Modules/cache/DOMCacheEngine.cpp_sec1
132
    return WTF::switchOn(body, [](const Ref<FormData>& formData) -> ResponseBody {
132
    return WTF::switchOn(body, [](const Ref<FormData>& formData) -> ResponseBody {
133
        return formData->isolatedCopy();
133
        return formData->isolatedCopy();
134
    }, [](const Ref<SharedBuffer>& buffer) -> ResponseBody {
134
    }, [](const Ref<SharedBuffer>& buffer) -> ResponseBody {
135
        return buffer->copy();
135
        return buffer.copyRef(); // SharedBuffer are immutable and can be returned as-is.
136
    }, [](const std::nullptr_t&) -> ResponseBody {
136
    }, [](const std::nullptr_t&) -> ResponseBody {
137
        return DOMCacheEngine::ResponseBody { };
137
        return DOMCacheEngine::ResponseBody { };
138
    });
138
    });
- a/Source/WebCore/Modules/encryptedmedia/CDM.cpp -3 / +3 lines
Lines 135-151 bool CDM::supportsInitDataType(const AtomString& initDataType) const a/Source/WebCore/Modules/encryptedmedia/CDM.cpp_sec1
135
    return m_private && m_private->supportedInitDataTypes().contains(initDataType);
135
    return m_private && m_private->supportedInitDataTypes().contains(initDataType);
136
}
136
}
137
137
138
RefPtr<SharedBuffer> CDM::sanitizeInitData(const AtomString& initDataType, const SharedBuffer& initData)
138
RefPtr<FragmentedSharedBuffer> CDM::sanitizeInitData(const AtomString& initDataType, const FragmentedSharedBuffer& initData)
139
{
139
{
140
    return InitDataRegistry::shared().sanitizeInitData(initDataType, initData);
140
    return InitDataRegistry::shared().sanitizeInitData(initDataType, initData);
141
}
141
}
142
142
143
bool CDM::supportsInitData(const AtomString& initDataType, const SharedBuffer& initData)
143
bool CDM::supportsInitData(const AtomString& initDataType, const FragmentedSharedBuffer& initData)
144
{
144
{
145
    return m_private && m_private->supportsInitData(initDataType, initData);
145
    return m_private && m_private->supportsInitData(initDataType, initData);
146
}
146
}
147
147
148
RefPtr<SharedBuffer> CDM::sanitizeResponse(const SharedBuffer& response)
148
RefPtr<FragmentedSharedBuffer> CDM::sanitizeResponse(const FragmentedSharedBuffer& response)
149
{
149
{
150
    if (!m_private)
150
    if (!m_private)
151
        return nullptr;
151
        return nullptr;
- a/Source/WebCore/Modules/encryptedmedia/CDM.h -4 / +4 lines
Lines 52-58 class CDMInstance; a/Source/WebCore/Modules/encryptedmedia/CDM.h_sec1
52
class CDMPrivate;
52
class CDMPrivate;
53
class Document;
53
class Document;
54
class ScriptExecutionContext;
54
class ScriptExecutionContext;
55
class SharedBuffer;
55
class FragmentedSharedBuffer;
56
56
57
class CDM : public RefCounted<CDM>, public CanMakeWeakPtr<CDM>, private ContextDestructionObserver {
57
class CDM : public RefCounted<CDM>, public CanMakeWeakPtr<CDM>, private ContextDestructionObserver {
58
public:
58
public:
Lines 73-82 public: a/Source/WebCore/Modules/encryptedmedia/CDM.h_sec2
73
    bool supportsSessions() const;
73
    bool supportsSessions() const;
74
    bool supportsInitDataType(const AtomString&) const;
74
    bool supportsInitDataType(const AtomString&) const;
75
75
76
    RefPtr<SharedBuffer> sanitizeInitData(const AtomString& initDataType, const SharedBuffer&);
76
    RefPtr<FragmentedSharedBuffer> sanitizeInitData(const AtomString& initDataType, const FragmentedSharedBuffer&);
77
    bool supportsInitData(const AtomString& initDataType, const SharedBuffer&);
77
    bool supportsInitData(const AtomString& initDataType, const FragmentedSharedBuffer&);
78
78
79
    RefPtr<SharedBuffer> sanitizeResponse(const SharedBuffer&);
79
    RefPtr<FragmentedSharedBuffer> sanitizeResponse(const FragmentedSharedBuffer&);
80
80
81
    std::optional<String> sanitizeSessionId(const String& sessionId);
81
    std::optional<String> sanitizeSessionId(const String& sessionId);
82
82
- a/Source/WebCore/Modules/encryptedmedia/CDMClient.h -2 / +2 lines
Lines 36-49 a/Source/WebCore/Modules/encryptedmedia/CDMClient.h_sec1
36
namespace WebCore {
36
namespace WebCore {
37
37
38
class CDMInstance;
38
class CDMInstance;
39
class SharedBuffer;
39
class FragmentedSharedBuffer;
40
40
41
class CDMClient : public CanMakeWeakPtr<CDMClient> {
41
class CDMClient : public CanMakeWeakPtr<CDMClient> {
42
public:
42
public:
43
    virtual ~CDMClient() = default;
43
    virtual ~CDMClient() = default;
44
44
45
    virtual void cdmClientAttemptToResumePlaybackIfNecessary() = 0;
45
    virtual void cdmClientAttemptToResumePlaybackIfNecessary() = 0;
46
    virtual void cdmClientUnrequestedInitializationDataReceived(const String&, Ref<SharedBuffer>&&) = 0;
46
    virtual void cdmClientUnrequestedInitializationDataReceived(const String&, Ref<FragmentedSharedBuffer>&&) = 0;
47
};
47
};
48
48
49
} // namespace WebCore
49
} // namespace WebCore
- a/Source/WebCore/Modules/encryptedmedia/InitDataRegistry.cpp -15 / +15 lines
Lines 54-66 namespace { a/Source/WebCore/Modules/encryptedmedia/InitDataRegistry.cpp_sec1
54
    const uint32_t kKeyIdsMaxKeyIdSizeInBytes = 512;
54
    const uint32_t kKeyIdsMaxKeyIdSizeInBytes = 512;
55
}
55
}
56
56
57
static std::optional<Vector<Ref<SharedBuffer>>> extractKeyIDsKeyids(const SharedBuffer& buffer)
57
static std::optional<Vector<Ref<FragmentedSharedBuffer>>> extractKeyIDsKeyids(const FragmentedSharedBuffer& buffer)
58
{
58
{
59
    // 1. Format
59
    // 1. Format
60
    // https://w3c.github.io/encrypted-media/format-registry/initdata/keyids.html#format
60
    // https://w3c.github.io/encrypted-media/format-registry/initdata/keyids.html#format
61
    if (buffer.size() > std::numeric_limits<unsigned>::max())
61
    if (buffer.size() > std::numeric_limits<unsigned>::max())
62
        return std::nullopt;
62
        return std::nullopt;
63
    String json { buffer.data(), static_cast<unsigned>(buffer.size()) };
63
    String json { buffer.makeContiguous()->data(), static_cast<unsigned>(buffer.size()) };
64
64
65
    auto value = JSON::Value::parseJSON(json);
65
    auto value = JSON::Value::parseJSON(json);
66
    if (!value)
66
    if (!value)
Lines 74-80 static std::optional<Vector<Ref<SharedBuffer>>> extractKeyIDsKeyids(const Shared a/Source/WebCore/Modules/encryptedmedia/InitDataRegistry.cpp_sec2
74
    if (!kidsArray)
74
    if (!kidsArray)
75
        return std::nullopt;
75
        return std::nullopt;
76
76
77
    Vector<Ref<SharedBuffer>> keyIDs;
77
    Vector<Ref<FragmentedSharedBuffer>> keyIDs;
78
    for (auto& value : *kidsArray) {
78
    for (auto& value : *kidsArray) {
79
        auto keyID = value->asString();
79
        auto keyID = value->asString();
80
        if (!keyID)
80
        if (!keyID)
Lines 93-99 static std::optional<Vector<Ref<SharedBuffer>>> extractKeyIDsKeyids(const Shared a/Source/WebCore/Modules/encryptedmedia/InitDataRegistry.cpp_sec3
93
    return keyIDs;
93
    return keyIDs;
94
}
94
}
95
95
96
static RefPtr<SharedBuffer> sanitizeKeyids(const SharedBuffer& buffer)
96
static RefPtr<FragmentedSharedBuffer> sanitizeKeyids(const FragmentedSharedBuffer& buffer)
97
{
97
{
98
    // 1. Format
98
    // 1. Format
99
    // https://w3c.github.io/encrypted-media/format-registry/initdata/keyids.html#format
99
    // https://w3c.github.io/encrypted-media/format-registry/initdata/keyids.html#format
Lines 104-117 static RefPtr<SharedBuffer> sanitizeKeyids(const SharedBuffer& buffer) a/Source/WebCore/Modules/encryptedmedia/InitDataRegistry.cpp_sec4
104
    auto object = JSON::Object::create();
104
    auto object = JSON::Object::create();
105
    auto kidsArray = JSON::Array::create();
105
    auto kidsArray = JSON::Array::create();
106
    for (auto& buffer : keyIDBuffer.value())
106
    for (auto& buffer : keyIDBuffer.value())
107
        kidsArray->pushString(base64URLEncodeToString(buffer->data(), buffer->size()));
107
        kidsArray->pushString(base64URLEncodeToString(buffer->makeContiguous()->data(), buffer->size()));
108
    object->setArray("kids", WTFMove(kidsArray));
108
    object->setArray("kids", WTFMove(kidsArray));
109
109
110
    CString jsonData = object->toJSONString().utf8();
110
    CString jsonData = object->toJSONString().utf8();
111
    return SharedBuffer::create(jsonData.data(), jsonData.length());
111
    return SharedBuffer::create(jsonData.data(), jsonData.length());
112
}
112
}
113
113
114
std::optional<Vector<std::unique_ptr<ISOProtectionSystemSpecificHeaderBox>>> InitDataRegistry::extractPsshBoxesFromCenc(const SharedBuffer& buffer)
114
std::optional<Vector<std::unique_ptr<ISOProtectionSystemSpecificHeaderBox>>> InitDataRegistry::extractPsshBoxesFromCenc(const FragmentedSharedBuffer& buffer)
115
{
115
{
116
    // 4. Common SystemID and PSSH Box Format
116
    // 4. Common SystemID and PSSH Box Format
117
    // https://w3c.github.io/encrypted-media/format-registry/initdata/cenc.html#common-system
117
    // https://w3c.github.io/encrypted-media/format-registry/initdata/cenc.html#common-system
Lines 151-159 std::optional<Vector<std::unique_ptr<ISOProtectionSystemSpecificHeaderBox>>> Ini a/Source/WebCore/Modules/encryptedmedia/InitDataRegistry.cpp_sec5
151
    return psshBoxes;
151
    return psshBoxes;
152
}
152
}
153
153
154
std::optional<Vector<Ref<SharedBuffer>>> InitDataRegistry::extractKeyIDsCenc(const SharedBuffer& buffer)
154
std::optional<Vector<Ref<FragmentedSharedBuffer>>> InitDataRegistry::extractKeyIDsCenc(const FragmentedSharedBuffer& buffer)
155
{
155
{
156
    Vector<Ref<SharedBuffer>> keyIDs;
156
    Vector<Ref<FragmentedSharedBuffer>> keyIDs;
157
157
158
    auto psshBoxes = extractPsshBoxesFromCenc(buffer);
158
    auto psshBoxes = extractPsshBoxesFromCenc(buffer);
159
    if (!psshBoxes)
159
    if (!psshBoxes)
Lines 185-191 std::optional<Vector<Ref<SharedBuffer>>> InitDataRegistry::extractKeyIDsCenc(con a/Source/WebCore/Modules/encryptedmedia/InitDataRegistry.cpp_sec6
185
    return keyIDs;
185
    return keyIDs;
186
}
186
}
187
187
188
RefPtr<SharedBuffer> InitDataRegistry::sanitizeCenc(const SharedBuffer& buffer)
188
RefPtr<FragmentedSharedBuffer> InitDataRegistry::sanitizeCenc(const FragmentedSharedBuffer& buffer)
189
{
189
{
190
    // 4. Common SystemID and PSSH Box Format
190
    // 4. Common SystemID and PSSH Box Format
191
    // https://w3c.github.io/encrypted-media/format-registry/initdata/cenc.html#common-system
191
    // https://w3c.github.io/encrypted-media/format-registry/initdata/cenc.html#common-system
Lines 195-201 RefPtr<SharedBuffer> InitDataRegistry::sanitizeCenc(const SharedBuffer& buffer) a/Source/WebCore/Modules/encryptedmedia/InitDataRegistry.cpp_sec7
195
    return buffer.copy();
195
    return buffer.copy();
196
}
196
}
197
197
198
static RefPtr<SharedBuffer> sanitizeWebM(const SharedBuffer& buffer)
198
static RefPtr<FragmentedSharedBuffer> sanitizeWebM(const FragmentedSharedBuffer& buffer)
199
{
199
{
200
    // Check if the buffer is a valid WebM initData.
200
    // Check if the buffer is a valid WebM initData.
201
    // The WebM initData is the ContentEncKeyID, so should be less than kWebMMaxContentEncKeyIDSize.
201
    // The WebM initData is the ContentEncKeyID, so should be less than kWebMMaxContentEncKeyIDSize.
Lines 205-214 static RefPtr<SharedBuffer> sanitizeWebM(const SharedBuffer& buffer) a/Source/WebCore/Modules/encryptedmedia/InitDataRegistry.cpp_sec8
205
    return buffer.copy();
205
    return buffer.copy();
206
}
206
}
207
207
208
static std::optional<Vector<Ref<SharedBuffer>>> extractKeyIDsWebM(const SharedBuffer& buffer)
208
static std::optional<Vector<Ref<FragmentedSharedBuffer>>> extractKeyIDsWebM(const FragmentedSharedBuffer& buffer)
209
{
209
{
210
    Vector<Ref<SharedBuffer>> keyIDs;
210
    Vector<Ref<FragmentedSharedBuffer>> keyIDs;
211
    RefPtr<SharedBuffer> sanitizedBuffer = sanitizeWebM(buffer);
211
    RefPtr<FragmentedSharedBuffer> sanitizedBuffer = sanitizeWebM(buffer);
212
    if (!sanitizedBuffer)
212
    if (!sanitizedBuffer)
213
        return std::nullopt;
213
        return std::nullopt;
214
214
Lines 233-239 InitDataRegistry::InitDataRegistry() a/Source/WebCore/Modules/encryptedmedia/InitDataRegistry.cpp_sec9
233
233
234
InitDataRegistry::~InitDataRegistry() = default;
234
InitDataRegistry::~InitDataRegistry() = default;
235
235
236
RefPtr<SharedBuffer> InitDataRegistry::sanitizeInitData(const AtomString& initDataType, const SharedBuffer& buffer)
236
RefPtr<FragmentedSharedBuffer> InitDataRegistry::sanitizeInitData(const AtomString& initDataType, const FragmentedSharedBuffer& buffer)
237
{
237
{
238
    auto iter = m_types.find(initDataType);
238
    auto iter = m_types.find(initDataType);
239
    if (iter == m_types.end() || !iter->value.sanitizeInitData)
239
    if (iter == m_types.end() || !iter->value.sanitizeInitData)
Lines 241-247 RefPtr<SharedBuffer> InitDataRegistry::sanitizeInitData(const AtomString& initDa a/Source/WebCore/Modules/encryptedmedia/InitDataRegistry.cpp_sec10
241
    return iter->value.sanitizeInitData(buffer);
241
    return iter->value.sanitizeInitData(buffer);
242
}
242
}
243
243
244
std::optional<Vector<Ref<SharedBuffer>>> InitDataRegistry::extractKeyIDs(const AtomString& initDataType, const SharedBuffer& buffer)
244
std::optional<Vector<Ref<FragmentedSharedBuffer>>> InitDataRegistry::extractKeyIDs(const AtomString& initDataType, const FragmentedSharedBuffer& buffer)
245
{
245
{
246
    auto iter = m_types.find(initDataType);
246
    auto iter = m_types.find(initDataType);
247
    if (iter == m_types.end() || !iter->value.sanitizeInitData)
247
    if (iter == m_types.end() || !iter->value.sanitizeInitData)
- a/Source/WebCore/Modules/encryptedmedia/InitDataRegistry.h -8 / +8 lines
Lines 38-56 a/Source/WebCore/Modules/encryptedmedia/InitDataRegistry.h_sec1
38
namespace WebCore {
38
namespace WebCore {
39
39
40
class ISOProtectionSystemSpecificHeaderBox;
40
class ISOProtectionSystemSpecificHeaderBox;
41
class SharedBuffer;
41
class FragmentedSharedBuffer;
42
42
43
class InitDataRegistry {
43
class InitDataRegistry {
44
public:
44
public:
45
    WEBCORE_EXPORT static InitDataRegistry& shared();
45
    WEBCORE_EXPORT static InitDataRegistry& shared();
46
    friend class NeverDestroyed<InitDataRegistry>;
46
    friend class NeverDestroyed<InitDataRegistry>;
47
47
48
    RefPtr<SharedBuffer> sanitizeInitData(const AtomString& initDataType, const SharedBuffer&);
48
    RefPtr<FragmentedSharedBuffer> sanitizeInitData(const AtomString& initDataType, const FragmentedSharedBuffer&);
49
    WEBCORE_EXPORT std::optional<Vector<Ref<SharedBuffer>>> extractKeyIDs(const AtomString& initDataType, const SharedBuffer&);
49
    WEBCORE_EXPORT std::optional<Vector<Ref<FragmentedSharedBuffer>>> extractKeyIDs(const AtomString& initDataType, const FragmentedSharedBuffer&);
50
50
51
    struct InitDataTypeCallbacks {
51
    struct InitDataTypeCallbacks {
52
        using SanitizeInitDataCallback = Function<RefPtr<SharedBuffer>(const SharedBuffer&)>;
52
        using SanitizeInitDataCallback = Function<RefPtr<FragmentedSharedBuffer>(const FragmentedSharedBuffer&)>;
53
        using ExtractKeyIDsCallback = Function<std::optional<Vector<Ref<SharedBuffer>>>(const SharedBuffer&)>;
53
        using ExtractKeyIDsCallback = Function<std::optional<Vector<Ref<FragmentedSharedBuffer>>>(const FragmentedSharedBuffer&)>;
54
54
55
        SanitizeInitDataCallback sanitizeInitData;
55
        SanitizeInitDataCallback sanitizeInitData;
56
        ExtractKeyIDsCallback extractKeyIDs;
56
        ExtractKeyIDsCallback extractKeyIDs;
Lines 61-69 public: a/Source/WebCore/Modules/encryptedmedia/InitDataRegistry.h_sec2
61
    static const AtomString& keyidsName();
61
    static const AtomString& keyidsName();
62
    static const AtomString& webmName();
62
    static const AtomString& webmName();
63
63
64
    static std::optional<Vector<std::unique_ptr<ISOProtectionSystemSpecificHeaderBox>>> extractPsshBoxesFromCenc(const SharedBuffer&);
64
    static std::optional<Vector<std::unique_ptr<ISOProtectionSystemSpecificHeaderBox>>> extractPsshBoxesFromCenc(const FragmentedSharedBuffer&);
65
    static std::optional<Vector<Ref<SharedBuffer>>> extractKeyIDsCenc(const SharedBuffer&);
65
    static std::optional<Vector<Ref<FragmentedSharedBuffer>>> extractKeyIDsCenc(const FragmentedSharedBuffer&);
66
    static RefPtr<SharedBuffer> sanitizeCenc(const SharedBuffer&);
66
    static RefPtr<FragmentedSharedBuffer> sanitizeCenc(const FragmentedSharedBuffer&);
67
67
68
private:
68
private:
69
    InitDataRegistry();
69
    InitDataRegistry();
- a/Source/WebCore/Modules/encryptedmedia/MediaKeySession.cpp -6 / +6 lines
Lines 176-182 void MediaKeySession::generateRequest(const AtomString& initDataType, const Buff a/Source/WebCore/Modules/encryptedmedia/MediaKeySession.cpp_sec1
176
    queueTaskKeepingObjectAlive(*this, TaskSource::Networking, [this, weakThis = WeakPtr { *this }, initData = SharedBuffer::create(initData.data(), initData.length()), initDataType, promise = WTFMove(promise), identifier = WTFMove(identifier)] () mutable {
176
    queueTaskKeepingObjectAlive(*this, TaskSource::Networking, [this, weakThis = WeakPtr { *this }, initData = SharedBuffer::create(initData.data(), initData.length()), initDataType, promise = WTFMove(promise), identifier = WTFMove(identifier)] () mutable {
177
        // 10.1. If the init data is not valid for initDataType, reject promise with a newly created TypeError.
177
        // 10.1. If the init data is not valid for initDataType, reject promise with a newly created TypeError.
178
        // 10.2. Let sanitized init data be a validated and sanitized version of init data.
178
        // 10.2. Let sanitized init data be a validated and sanitized version of init data.
179
        RefPtr<SharedBuffer> sanitizedInitData = m_implementation->sanitizeInitData(initDataType, initData);
179
        RefPtr<FragmentedSharedBuffer> sanitizedInitData = m_implementation->sanitizeInitData(initDataType, initData);
180
180
181
        // 10.3. If the preceding step failed, reject promise with a newly created TypeError.
181
        // 10.3. If the preceding step failed, reject promise with a newly created TypeError.
182
        if (!sanitizedInitData) {
182
        if (!sanitizedInitData) {
Lines 223-229 void MediaKeySession::generateRequest(const AtomString& initDataType, const Buff a/Source/WebCore/Modules/encryptedmedia/MediaKeySession.cpp_sec2
223
            m_latestDecryptTime = 0;
223
            m_latestDecryptTime = 0;
224
        }
224
        }
225
225
226
        m_instanceSession->requestLicense(m_sessionType, initDataType, sanitizedInitData.releaseNonNull(), [this, weakThis, promise = WTFMove(promise), identifier = WTFMove(identifier)] (Ref<SharedBuffer>&& message, const String& sessionId, bool needsIndividualization, CDMInstanceSession::SuccessValue succeeded) mutable {
226
        m_instanceSession->requestLicense(m_sessionType, initDataType, sanitizedInitData.releaseNonNull(), [this, weakThis, promise = WTFMove(promise), identifier = WTFMove(identifier)] (Ref<FragmentedSharedBuffer>&& message, const String& sessionId, bool needsIndividualization, CDMInstanceSession::SuccessValue succeeded) mutable {
227
            if (!weakThis)
227
            if (!weakThis)
228
                return;
228
                return;
229
229
Lines 422-428 void MediaKeySession::update(const BufferSource& response, Ref<DeferredPromise>& a/Source/WebCore/Modules/encryptedmedia/MediaKeySession.cpp_sec3
422
    // 6. Run the following steps in parallel:
422
    // 6. Run the following steps in parallel:
423
    queueTaskKeepingObjectAlive(*this, TaskSource::Networking, [this, weakThis = WeakPtr { *this }, response = SharedBuffer::create(response.data(), response.length()), promise = WTFMove(promise), identifier = WTFMove(identifier)] () mutable {
423
    queueTaskKeepingObjectAlive(*this, TaskSource::Networking, [this, weakThis = WeakPtr { *this }, response = SharedBuffer::create(response.data(), response.length()), promise = WTFMove(promise), identifier = WTFMove(identifier)] () mutable {
424
        // 6.1. Let sanitized response be a validated and/or sanitized version of response copy.
424
        // 6.1. Let sanitized response be a validated and/or sanitized version of response copy.
425
        RefPtr<SharedBuffer> sanitizedResponse = m_implementation->sanitizeResponse(response);
425
        RefPtr<FragmentedSharedBuffer> sanitizedResponse = m_implementation->sanitizeResponse(response);
426
426
427
        // 6.2. If the preceding step failed, or if sanitized response is empty, reject promise with a newly created TypeError.
427
        // 6.2. If the preceding step failed, or if sanitized response is empty, reject promise with a newly created TypeError.
428
        if (!sanitizedResponse || sanitizedResponse->isEmpty()) {
428
        if (!sanitizedResponse || sanitizedResponse->isEmpty()) {
Lines 601-607 void MediaKeySession::remove(Ref<DeferredPromise>&& promise) a/Source/WebCore/Modules/encryptedmedia/MediaKeySession.cpp_sec4
601
        // 4.3. Let message type be null.
601
        // 4.3. Let message type be null.
602
602
603
        // 4.4. Use the cdm to execute the following steps:
603
        // 4.4. Use the cdm to execute the following steps:
604
        m_instanceSession->removeSessionData(m_sessionId, m_sessionType, [this, weakThis, promise = WTFMove(promise), identifier = WTFMove(identifier)] (CDMInstanceSession::KeyStatusVector&& keys, std::optional<Ref<SharedBuffer>>&& message, CDMInstanceSession::SuccessValue succeeded) mutable {
604
        m_instanceSession->removeSessionData(m_sessionId, m_sessionType, [this, weakThis, promise = WTFMove(promise), identifier = WTFMove(identifier)] (CDMInstanceSession::KeyStatusVector&& keys, std::optional<Ref<FragmentedSharedBuffer>>&& message, CDMInstanceSession::SuccessValue succeeded) mutable {
605
            if (!weakThis)
605
            if (!weakThis)
606
                return;
606
                return;
607
607
Lines 649-655 void MediaKeySession::remove(Ref<DeferredPromise>&& promise) a/Source/WebCore/Modules/encryptedmedia/MediaKeySession.cpp_sec5
649
    // 5. Return promise.
649
    // 5. Return promise.
650
}
650
}
651
651
652
void MediaKeySession::enqueueMessage(MediaKeyMessageType messageType, const SharedBuffer& message)
652
void MediaKeySession::enqueueMessage(MediaKeyMessageType messageType, const FragmentedSharedBuffer& message)
653
{
653
{
654
    // 6.4.1 Queue a "message" Event
654
    // 6.4.1 Queue a "message" Event
655
    // https://w3c.github.io/encrypted-media/#queue-message
655
    // https://w3c.github.io/encrypted-media/#queue-message
Lines 716-722 void MediaKeySession::updateKeyStatuses(CDMInstanceSession::KeyStatusVector&& in a/Source/WebCore/Modules/encryptedmedia/MediaKeySession.cpp_sec6
716
        });
716
        });
717
}
717
}
718
718
719
void MediaKeySession::sendMessage(CDMMessageType messageType, Ref<SharedBuffer>&& message)
719
void MediaKeySession::sendMessage(CDMMessageType messageType, Ref<FragmentedSharedBuffer>&& message)
720
{
720
{
721
    enqueueMessage(messageType, message);
721
    enqueueMessage(messageType, message);
722
}
722
}
- a/Source/WebCore/Modules/encryptedmedia/MediaKeySession.h -6 / +6 lines
Lines 57-63 class CDM; a/Source/WebCore/Modules/encryptedmedia/MediaKeySession.h_sec1
57
class DeferredPromise;
57
class DeferredPromise;
58
class MediaKeyStatusMap;
58
class MediaKeyStatusMap;
59
class MediaKeys;
59
class MediaKeys;
60
class SharedBuffer;
60
class FragmentedSharedBuffer;
61
61
62
template<typename IDLType> class DOMPromiseProxy;
62
template<typename IDLType> class DOMPromiseProxy;
63
63
Lines 87-106 public: a/Source/WebCore/Modules/encryptedmedia/MediaKeySession.h_sec2
87
    using ClosedPromise = DOMPromiseProxy<IDLUndefined>;
87
    using ClosedPromise = DOMPromiseProxy<IDLUndefined>;
88
    ClosedPromise& closed() { return m_closedPromise.get(); }
88
    ClosedPromise& closed() { return m_closedPromise.get(); }
89
89
90
    const Vector<std::pair<Ref<SharedBuffer>, MediaKeyStatus>>& statuses() const { return m_statuses; }
90
    const Vector<std::pair<Ref<FragmentedSharedBuffer>, MediaKeyStatus>>& statuses() const { return m_statuses; }
91
91
92
    unsigned internalInstanceSessionObjectRefCount() const { return m_instanceSession->refCount(); }
92
    unsigned internalInstanceSessionObjectRefCount() const { return m_instanceSession->refCount(); }
93
93
94
private:
94
private:
95
    MediaKeySession(Document&, WeakPtr<MediaKeys>&&, MediaKeySessionType, bool useDistinctiveIdentifier, Ref<CDM>&&, Ref<CDMInstanceSession>&&);
95
    MediaKeySession(Document&, WeakPtr<MediaKeys>&&, MediaKeySessionType, bool useDistinctiveIdentifier, Ref<CDM>&&, Ref<CDMInstanceSession>&&);
96
    void enqueueMessage(MediaKeyMessageType, const SharedBuffer&);
96
    void enqueueMessage(MediaKeyMessageType, const FragmentedSharedBuffer&);
97
    void updateExpiration(double);
97
    void updateExpiration(double);
98
    void sessionClosed();
98
    void sessionClosed();
99
    String mediaKeysStorageDirectory() const;
99
    String mediaKeysStorageDirectory() const;
100
100
101
    // CDMInstanceSessionClient
101
    // CDMInstanceSessionClient
102
    void updateKeyStatuses(CDMInstanceSessionClient::KeyStatusVector&&) override;
102
    void updateKeyStatuses(CDMInstanceSessionClient::KeyStatusVector&&) override;
103
    void sendMessage(CDMMessageType, Ref<SharedBuffer>&& message) final;
103
    void sendMessage(CDMMessageType, Ref<FragmentedSharedBuffer>&& message) final;
104
    void sessionIdChanged(const String&) final;
104
    void sessionIdChanged(const String&) final;
105
    PlatformDisplayID displayID() final;
105
    PlatformDisplayID displayID() final;
106
106
Lines 140-149 private: a/Source/WebCore/Modules/encryptedmedia/MediaKeySession.h_sec3
140
    MediaKeySessionType m_sessionType;
140
    MediaKeySessionType m_sessionType;
141
    Ref<CDM> m_implementation;
141
    Ref<CDM> m_implementation;
142
    Ref<CDMInstanceSession> m_instanceSession;
142
    Ref<CDMInstanceSession> m_instanceSession;
143
    Vector<Ref<SharedBuffer>> m_recordOfKeyUsage;
143
    Vector<Ref<FragmentedSharedBuffer>> m_recordOfKeyUsage;
144
    double m_firstDecryptTime { 0 };
144
    double m_firstDecryptTime { 0 };
145
    double m_latestDecryptTime { 0 };
145
    double m_latestDecryptTime { 0 };
146
    Vector<std::pair<Ref<SharedBuffer>, MediaKeyStatus>> m_statuses;
146
    Vector<std::pair<Ref<FragmentedSharedBuffer>, MediaKeyStatus>> m_statuses;
147
147
148
    using DisplayChangedObserver = Observer<void(PlatformDisplayID)>;
148
    using DisplayChangedObserver = Observer<void(PlatformDisplayID)>;
149
    DisplayChangedObserver m_displayChangedObserver;
149
    DisplayChangedObserver m_displayChangedObserver;
- a/Source/WebCore/Modules/encryptedmedia/MediaKeyStatusMap.cpp -3 / +3 lines
Lines 56-67 unsigned long MediaKeyStatusMap::size() a/Source/WebCore/Modules/encryptedmedia/MediaKeyStatusMap.cpp_sec1
56
    return m_session->statuses().size();
56
    return m_session->statuses().size();
57
}
57
}
58
58
59
static bool keyIdsMatch(const SharedBuffer& a, const BufferSource& b)
59
static bool keyIdsMatch(const FragmentedSharedBuffer& a, const BufferSource& b)
60
{
60
{
61
    auto length = a.size();
61
    auto length = a.size();
62
    if (!length || length != b.length())
62
    if (!length || length != b.length())
63
        return false;
63
        return false;
64
    return !std::memcmp(a.data(), b.data(), length);
64
    return !std::memcmp(a.makeContiguous()->data(), b.data(), length);
65
}
65
}
66
66
67
bool MediaKeyStatusMap::has(const BufferSource& keyId)
67
bool MediaKeyStatusMap::has(const BufferSource& keyId)
Lines 103-109 std::optional<KeyValuePair<BufferSource::VariantType, MediaKeyStatus>> MediaKeyS a/Source/WebCore/Modules/encryptedmedia/MediaKeyStatusMap.cpp_sec2
103
        return std::nullopt;
103
        return std::nullopt;
104
104
105
    auto& pair = statuses[m_index++];
105
    auto& pair = statuses[m_index++];
106
    auto buffer = ArrayBuffer::create(pair.first->data(), pair.first->size());
106
    auto buffer = ArrayBuffer::create(pair.first->makeContiguous()->data(), pair.first->size());
107
    return KeyValuePair<BufferSource::VariantType, MediaKeyStatus> { RefPtr<ArrayBuffer>(WTFMove(buffer)), pair.second };
107
    return KeyValuePair<BufferSource::VariantType, MediaKeyStatus> { RefPtr<ArrayBuffer>(WTFMove(buffer)), pair.second };
108
}
108
}
109
109
- a/Source/WebCore/Modules/encryptedmedia/MediaKeyStatusMap.h -1 / +1 lines
Lines 38-44 a/Source/WebCore/Modules/encryptedmedia/MediaKeyStatusMap.h_sec1
38
namespace WebCore {
38
namespace WebCore {
39
39
40
class MediaKeySession;
40
class MediaKeySession;
41
class SharedBuffer;
41
class FragmentedSharedBuffer;
42
42
43
class MediaKeyStatusMap : public RefCounted<MediaKeyStatusMap> {
43
class MediaKeyStatusMap : public RefCounted<MediaKeyStatusMap> {
44
public:
44
public:
- a/Source/WebCore/Modules/encryptedmedia/MediaKeys.cpp -1 / +1 lines
Lines 177-183 bool MediaKeys::hasOpenSessions() const a/Source/WebCore/Modules/encryptedmedia/MediaKeys.cpp_sec1
177
        });
177
        });
178
}
178
}
179
179
180
void MediaKeys::unrequestedInitializationDataReceived(const String& initDataType, Ref<SharedBuffer>&& initData)
180
void MediaKeys::unrequestedInitializationDataReceived(const String& initDataType, Ref<FragmentedSharedBuffer>&& initData)
181
{
181
{
182
    for (auto& cdmClient : m_cdmClients)
182
    for (auto& cdmClient : m_cdmClients)
183
        cdmClient.cdmClientUnrequestedInitializationDataReceived(initDataType, initData.copyRef());
183
        cdmClient.cdmClientUnrequestedInitializationDataReceived(initDataType, initData.copyRef());
- a/Source/WebCore/Modules/encryptedmedia/MediaKeys.h -1 / +1 lines
Lines 86-92 protected: a/Source/WebCore/Modules/encryptedmedia/MediaKeys.h_sec1
86
    MediaKeys(Document&, bool useDistinctiveIdentifier, bool persistentStateAllowed, const Vector<MediaKeySessionType>&, Ref<CDM>&&, Ref<CDMInstance>&&);
86
    MediaKeys(Document&, bool useDistinctiveIdentifier, bool persistentStateAllowed, const Vector<MediaKeySessionType>&, Ref<CDM>&&, Ref<CDMInstance>&&);
87
87
88
    // CDMInstanceClient
88
    // CDMInstanceClient
89
    void unrequestedInitializationDataReceived(const String&, Ref<SharedBuffer>&&) final;
89
    void unrequestedInitializationDataReceived(const String&, Ref<FragmentedSharedBuffer>&&) final;
90
90
91
#if !RELEASE_LOG_DISABLED
91
#if !RELEASE_LOG_DISABLED
92
    const Logger& logger() const { return m_logger; }
92
    const Logger& logger() const { return m_logger; }
- a/Source/WebCore/Modules/fetch/FetchBody.cpp -3 / +3 lines
Lines 235-241 void FetchBody::consumeBlob(FetchBodyOwner& owner, Ref<DeferredPromise>&& promis a/Source/WebCore/Modules/fetch/FetchBody.cpp_sec1
235
void FetchBody::consumeFormData(FetchBodyOwner& owner, Ref<DeferredPromise>&& promise)
235
void FetchBody::consumeFormData(FetchBodyOwner& owner, Ref<DeferredPromise>&& promise)
236
{
236
{
237
    if (auto sharedBuffer = formDataBody().asSharedBuffer()) {
237
    if (auto sharedBuffer = formDataBody().asSharedBuffer()) {
238
        m_consumer.resolveWithData(WTFMove(promise), owner.contentType(), sharedBuffer->data(), sharedBuffer->size());
238
        m_consumer.resolveWithData(WTFMove(promise), owner.contentType(), sharedBuffer->makeContiguous()->data(), sharedBuffer->size());
239
        m_data = nullptr;
239
        m_data = nullptr;
240
    } else {
240
    } else {
241
        // FIXME: If the form data contains blobs, load them like we do other blobs.
241
        // FIXME: If the form data contains blobs, load them like we do other blobs.
Lines 272-278 RefPtr<FormData> FetchBody::bodyAsFormData() const a/Source/WebCore/Modules/fetch/FetchBody.cpp_sec2
272
    if (isFormData())
272
    if (isFormData())
273
        return &const_cast<FormData&>(formDataBody());
273
        return &const_cast<FormData&>(formDataBody());
274
    if (auto* data = m_consumer.data())
274
    if (auto* data = m_consumer.data())
275
        return FormData::create(data->data(), data->size());
275
        return FormData::create(data->makeContiguous()->data(), data->size());
276
276
277
    ASSERT_NOT_REACHED();
277
    ASSERT_NOT_REACHED();
278
    return nullptr;
278
    return nullptr;
Lines 284-290 FetchBody::TakenData FetchBody::take() a/Source/WebCore/Modules/fetch/FetchBody.cpp_sec3
284
        auto buffer = m_consumer.takeData();
284
        auto buffer = m_consumer.takeData();
285
        if (!buffer)
285
        if (!buffer)
286
            return nullptr;
286
            return nullptr;
287
        return buffer.releaseNonNull();
287
        return buffer->makeContiguous();
288
    }
288
    }
289
289
290
    if (isBlob()) {
290
    if (isBlob()) {
- a/Source/WebCore/Modules/fetch/FetchBodyConsumer.cpp -25 / +25 lines
Lines 242-248 static void resolveWithTypeAndData(Ref<DeferredPromise>&& promise, FetchBodyCons a/Source/WebCore/Modules/fetch/FetchBodyConsumer.cpp_sec1
242
242
243
void FetchBodyConsumer::clean()
243
void FetchBodyConsumer::clean()
244
{
244
{
245
    m_buffer = nullptr;
245
    m_buffer.reset();
246
    resetConsumePromise();
246
    resetConsumePromise();
247
    if (m_sink) {
247
    if (m_sink) {
248
        m_sink->clearCallback();
248
        m_sink->clearCallback();
Lines 266-281 void FetchBodyConsumer::resolve(Ref<DeferredPromise>&& promise, const String& co a/Source/WebCore/Modules/fetch/FetchBodyConsumer.cpp_sec2
266
{
266
{
267
    if (stream) {
267
    if (stream) {
268
        ASSERT(!m_sink);
268
        ASSERT(!m_sink);
269
        m_sink = ReadableStreamToSharedBufferSink::create([promise = WTFMove(promise), data = SharedBuffer::create(), type = m_type, contentType](auto&& result) mutable {
269
        m_sink = ReadableStreamToSharedBufferSink::create([promise = WTFMove(promise), data = SharedBufferBuilder(), type = m_type, contentType](auto&& result) mutable {
270
            if (result.hasException()) {
270
            if (result.hasException()) {
271
                promise->reject(result.releaseException());
271
                promise->reject(result.releaseException());
272
                return;
272
                return;
273
            }
273
            }
274
274
275
            if (auto* chunk = result.returnValue())
275
            if (auto* chunk = result.returnValue())
276
                data->append(chunk->data(), chunk->size());
276
                data.append(chunk->data(), chunk->size());
277
            else
277
            else {
278
                resolveWithTypeAndData(WTFMove(promise), type, contentType, data->data(), data->size());
278
                auto buffer = data.take()->makeContiguous();
279
                resolveWithTypeAndData(WTFMove(promise), type, contentType, buffer->data(), buffer->size());
280
            }
279
        });
281
        });
280
        m_sink->pipeFrom(*stream);
282
        m_sink->pipeFrom(*stream);
281
        return;
283
        return;
Lines 306-312 void FetchBodyConsumer::resolve(Ref<DeferredPromise>&& promise, const String& co a/Source/WebCore/Modules/fetch/FetchBodyConsumer.cpp_sec3
306
        return;
308
        return;
307
    case FetchBodyConsumer::Type::FormData: {
309
    case FetchBodyConsumer::Type::FormData: {
308
        auto buffer = takeData();
310
        auto buffer = takeData();
309
        if (auto formData = packageFormData(context, contentType, buffer ? buffer->data() : nullptr, buffer ? buffer->size() : 0))
311
        if (auto formData = packageFormData(context, contentType, buffer ? buffer->makeContiguous()->data() : nullptr, buffer ? buffer->size() : 0))
310
            promise->resolve<IDLInterface<DOMFormData>>(*formData);
312
            promise->resolve<IDLInterface<DOMFormData>>(*formData);
311
        else
313
        else
312
            promise->reject(TypeError);
314
            promise->reject(TypeError);
Lines 324-339 void FetchBodyConsumer::append(const uint8_t* data, unsigned size) a/Source/WebCore/Modules/fetch/FetchBodyConsumer.cpp_sec4
324
        m_source->enqueue(ArrayBuffer::tryCreate(data, size));
326
        m_source->enqueue(ArrayBuffer::tryCreate(data, size));
325
        return;
327
        return;
326
    }
328
    }
327
    if (!m_buffer) {
329
    m_buffer.append(data, size);
328
        m_buffer = SharedBuffer::create(data, size);
329
        return;
330
    }
331
    m_buffer->append(data, size);
332
}
330
}
333
331
334
RefPtr<SharedBuffer> FetchBodyConsumer::takeData()
332
void FetchBodyConsumer::setData(Ref<FragmentedSharedBuffer>&& data)
335
{
333
{
336
    return WTFMove(m_buffer);
334
    m_buffer.reset();
335
    m_buffer.append(WTFMove(data));
336
}
337
338
RefPtr<FragmentedSharedBuffer> FetchBodyConsumer::takeData()
339
{
340
    if (!m_buffer)
341
        return nullptr;
342
    return m_buffer.take();
337
}
343
}
338
344
339
RefPtr<JSC::ArrayBuffer> FetchBodyConsumer::takeAsArrayBuffer()
345
RefPtr<JSC::ArrayBuffer> FetchBodyConsumer::takeAsArrayBuffer()
Lines 341-349 RefPtr<JSC::ArrayBuffer> FetchBodyConsumer::takeAsArrayBuffer() a/Source/WebCore/Modules/fetch/FetchBodyConsumer.cpp_sec5
341
    if (!m_buffer)
347
    if (!m_buffer)
342
        return ArrayBuffer::tryCreate(nullptr, 0);
348
        return ArrayBuffer::tryCreate(nullptr, 0);
343
349
344
    auto arrayBuffer = m_buffer->tryCreateArrayBuffer();
350
    return m_buffer.take()->tryCreateArrayBuffer();
345
    m_buffer = nullptr;
346
    return arrayBuffer;
347
}
351
}
348
352
349
Ref<Blob> FetchBodyConsumer::takeAsBlob(ScriptExecutionContext* context)
353
Ref<Blob> FetchBodyConsumer::takeAsBlob(ScriptExecutionContext* context)
Lines 351-359 Ref<Blob> FetchBodyConsumer::takeAsBlob(ScriptExecutionContext* context) a/Source/WebCore/Modules/fetch/FetchBodyConsumer.cpp_sec6
351
    if (!m_buffer)
355
    if (!m_buffer)
352
        return Blob::create(context, Vector<uint8_t>(), Blob::normalizedContentType(m_contentType));
356
        return Blob::create(context, Vector<uint8_t>(), Blob::normalizedContentType(m_contentType));
353
357
354
    auto buffer = std::exchange(m_buffer, nullptr);
358
    return blobFromData(context, m_buffer.take()->extractData(), m_contentType);
355
    auto data = buffer->extractData();
356
    return blobFromData(context, WTFMove(data), m_contentType);
357
}
359
}
358
360
359
String FetchBodyConsumer::takeAsText()
361
String FetchBodyConsumer::takeAsText()
Lines 362-369 String FetchBodyConsumer::takeAsText() a/Source/WebCore/Modules/fetch/FetchBodyConsumer.cpp_sec7
362
    if (!m_buffer)
364
    if (!m_buffer)
363
        return String();
365
        return String();
364
366
365
    auto text = TextResourceDecoder::textFromUTF8(m_buffer->data(), m_buffer->size());
367
    auto buffer = m_buffer.take()->makeContiguous();
366
    m_buffer = nullptr;
368
    auto text = TextResourceDecoder::textFromUTF8(buffer->data(), buffer->size());
367
    return text;
369
    return text;
368
}
370
}
369
371
Lines 383-392 void FetchBodyConsumer::resetConsumePromise() a/Source/WebCore/Modules/fetch/FetchBodyConsumer.cpp_sec8
383
void FetchBodyConsumer::setSource(Ref<FetchBodySource>&& source)
385
void FetchBodyConsumer::setSource(Ref<FetchBodySource>&& source)
384
{
386
{
385
    m_source = WTFMove(source);
387
    m_source = WTFMove(source);
386
    if (m_buffer) {
388
    if (m_buffer)
387
        m_source->enqueue(m_buffer->tryCreateArrayBuffer());
389
        m_source->enqueue(m_buffer.take()->tryCreateArrayBuffer());
388
        m_buffer = nullptr;
389
    }
390
}
390
}
391
391
392
void FetchBodyConsumer::loadingFailed(const Exception& exception)
392
void FetchBodyConsumer::loadingFailed(const Exception& exception)
- a/Source/WebCore/Modules/fetch/FetchBodyConsumer.h -4 / +4 lines
Lines 50-59 public: a/Source/WebCore/Modules/fetch/FetchBodyConsumer.h_sec1
50
    void append(const uint8_t* data, unsigned);
50
    void append(const uint8_t* data, unsigned);
51
51
52
    bool hasData() const { return !!m_buffer; }
52
    bool hasData() const { return !!m_buffer; }
53
    const SharedBuffer* data() const { return m_buffer.get(); }
53
    const FragmentedSharedBuffer* data() const { return m_buffer.get().get(); }
54
    void setData(Ref<SharedBuffer>&& data) { m_buffer = WTFMove(data); }
54
    void setData(Ref<FragmentedSharedBuffer>&&);
55
55
56
    RefPtr<SharedBuffer> takeData();
56
    RefPtr<FragmentedSharedBuffer> takeData();
57
    RefPtr<JSC::ArrayBuffer> takeAsArrayBuffer();
57
    RefPtr<JSC::ArrayBuffer> takeAsArrayBuffer();
58
    String takeAsText();
58
    String takeAsText();
59
59
Lines 82-88 private: a/Source/WebCore/Modules/fetch/FetchBodyConsumer.h_sec2
82
82
83
    Type m_type;
83
    Type m_type;
84
    String m_contentType;
84
    String m_contentType;
85
    RefPtr<SharedBuffer> m_buffer;
85
    SharedBufferBuilder m_buffer;
86
    RefPtr<DeferredPromise> m_consumePromise;
86
    RefPtr<DeferredPromise> m_consumePromise;
87
    RefPtr<ReadableStreamToSharedBufferSink> m_sink;
87
    RefPtr<ReadableStreamToSharedBufferSink> m_sink;
88
    RefPtr<FetchBodySource> m_source;
88
    RefPtr<FetchBodySource> m_source;
- a/Source/WebCore/Modules/fetch/FetchLoader.cpp -1 / +1 lines
Lines 135-141 void FetchLoader::stop() a/Source/WebCore/Modules/fetch/FetchLoader.cpp_sec1
135
        m_loader->cancel();
135
        m_loader->cancel();
136
}
136
}
137
137
138
RefPtr<SharedBuffer> FetchLoader::startStreaming()
138
RefPtr<FragmentedSharedBuffer> FetchLoader::startStreaming()
139
{
139
{
140
    ASSERT(m_consumer);
140
    ASSERT(m_consumer);
141
    auto firstChunk = m_consumer->takeData();
141
    auto firstChunk = m_consumer->takeData();
- a/Source/WebCore/Modules/fetch/FetchLoader.h -2 / +2 lines
Lines 39-52 class FetchBodyConsumer; a/Source/WebCore/Modules/fetch/FetchLoader.h_sec1
39
class FetchLoaderClient;
39
class FetchLoaderClient;
40
class FetchRequest;
40
class FetchRequest;
41
class ScriptExecutionContext;
41
class ScriptExecutionContext;
42
class SharedBuffer;
42
class FragmentedSharedBuffer;
43
43
44
class FetchLoader final : public ThreadableLoaderClient {
44
class FetchLoader final : public ThreadableLoaderClient {
45
public:
45
public:
46
    FetchLoader(FetchLoaderClient&, FetchBodyConsumer*);
46
    FetchLoader(FetchLoaderClient&, FetchBodyConsumer*);
47
    WEBCORE_EXPORT ~FetchLoader();
47
    WEBCORE_EXPORT ~FetchLoader();
48
48
49
    RefPtr<SharedBuffer> startStreaming();
49
    RefPtr<FragmentedSharedBuffer> startStreaming();
50
50
51
    void start(ScriptExecutionContext&, const FetchRequest&, const String&);
51
    void start(ScriptExecutionContext&, const FetchRequest&, const String&);
52
    void start(ScriptExecutionContext&, const Blob&);
52
    void start(ScriptExecutionContext&, const Blob&);
- a/Source/WebCore/Modules/fetch/FetchResponse.cpp -2 / +3 lines
Lines 400-406 void FetchResponse::BodyLoader::consumeDataByChunk(ConsumeDataByChunkCallback&& a/Source/WebCore/Modules/fetch/FetchResponse.cpp_sec1
400
    if (!data)
400
    if (!data)
401
        return;
401
        return;
402
402
403
    Span chunk { data->data(), data->size() };
403
    auto contiguousBuffer = data->makeContiguous();
404
    Span chunk { contiguousBuffer->data(), data->size() };
404
    m_consumeDataCallback(&chunk);
405
    m_consumeDataCallback(&chunk);
405
}
406
}
406
407
Lines 503-509 void FetchResponse::feedStream() a/Source/WebCore/Modules/fetch/FetchResponse.cpp_sec2
503
    closeStream();
504
    closeStream();
504
}
505
}
505
506
506
RefPtr<SharedBuffer> FetchResponse::BodyLoader::startStreaming()
507
RefPtr<FragmentedSharedBuffer> FetchResponse::BodyLoader::startStreaming()
507
{
508
{
508
    ASSERT(m_loader);
509
    ASSERT(m_loader);
509
    return m_loader->startStreaming();
510
    return m_loader->startStreaming();
- a/Source/WebCore/Modules/fetch/FetchResponse.h -1 / +1 lines
Lines 134-140 private: a/Source/WebCore/Modules/fetch/FetchResponse.h_sec1
134
134
135
        void consumeDataByChunk(ConsumeDataByChunkCallback&&);
135
        void consumeDataByChunk(ConsumeDataByChunkCallback&&);
136
136
137
        RefPtr<SharedBuffer> startStreaming();
137
        RefPtr<FragmentedSharedBuffer> startStreaming();
138
        NotificationCallback takeNotificationCallback() { return WTFMove(m_responseCallback); }
138
        NotificationCallback takeNotificationCallback() { return WTFMove(m_responseCallback); }
139
        ConsumeDataByChunkCallback takeConsumeDataCallback() { return WTFMove(m_consumeDataCallback); }
139
        ConsumeDataByChunkCallback takeConsumeDataCallback() { return WTFMove(m_consumeDataCallback); }
140
140
- a/Source/WebCore/Modules/highlight/AppHighlight.h -2 / +2 lines
Lines 38-44 enum class CreateNewGroupForHighlight : bool { No, Yes }; a/Source/WebCore/Modules/highlight/AppHighlight.h_sec1
38
enum class HighlightRequestOriginatedInApp : bool { No, Yes };
38
enum class HighlightRequestOriginatedInApp : bool { No, Yes };
39
39
40
struct AppHighlight {
40
struct AppHighlight {
41
    Ref<WebCore::SharedBuffer> highlight;
41
    Ref<WebCore::FragmentedSharedBuffer> highlight;
42
    std::optional<String> text;
42
    std::optional<String> text;
43
    CreateNewGroupForHighlight isNewGroup;
43
    CreateNewGroupForHighlight isNewGroup;
44
    HighlightRequestOriginatedInApp requestOriginatedInApp;
44
    HighlightRequestOriginatedInApp requestOriginatedInApp;
Lines 52-58 template<class Encoder> a/Source/WebCore/Modules/highlight/AppHighlight.h_sec2
52
void AppHighlight::encode(Encoder& encoder) const
52
void AppHighlight::encode(Encoder& encoder) const
53
{
53
{
54
    encoder << static_cast<size_t>(highlight->size());
54
    encoder << static_cast<size_t>(highlight->size());
55
    encoder.encodeFixedLengthData(highlight->data(), highlight->size(), 1);
55
    encoder.encodeFixedLengthData(highlight->makeContiguous()->data(), highlight->size(), 1);
56
56
57
    encoder << text;
57
    encoder << text;
58
58
- a/Source/WebCore/Modules/highlight/AppHighlightRangeData.cpp -3 / +4 lines
Lines 44-58 namespace WebCore { a/Source/WebCore/Modules/highlight/AppHighlightRangeData.cpp_sec1
44
44
45
constexpr uint64_t highlightFileSignature = 0x4141504832303231; // File Signature  (A)pple(AP)plication(H)ighlights(2021)
45
constexpr uint64_t highlightFileSignature = 0x4141504832303231; // File Signature  (A)pple(AP)plication(H)ighlights(2021)
46
46
47
std::optional<AppHighlightRangeData> AppHighlightRangeData::create(const SharedBuffer& buffer)
47
std::optional<AppHighlightRangeData> AppHighlightRangeData::create(const FragmentedSharedBuffer& buffer)
48
{
48
{
49
    auto decoder = buffer.decoder();
49
    auto contiguousBuffer = buffer.makeContiguous();
50
    auto decoder = contiguousBuffer->decoder();
50
    std::optional<AppHighlightRangeData> data;
51
    std::optional<AppHighlightRangeData> data;
51
    decoder >> data;
52
    decoder >> data;
52
    return data;
53
    return data;
53
}
54
}
54
55
55
Ref<SharedBuffer> AppHighlightRangeData::toSharedBuffer() const
56
Ref<FragmentedSharedBuffer> AppHighlightRangeData::toSharedBuffer() const
56
{
57
{
57
    WTF::Persistence::Encoder encoder;
58
    WTF::Persistence::Encoder encoder;
58
    encoder << *this;
59
    encoder << *this;
- a/Source/WebCore/Modules/highlight/AppHighlightRangeData.h -3 / +3 lines
Lines 33-44 namespace WebCore { a/Source/WebCore/Modules/highlight/AppHighlightRangeData.h_sec1
33
33
34
#if ENABLE(APP_HIGHLIGHTS)
34
#if ENABLE(APP_HIGHLIGHTS)
35
35
36
class SharedBuffer;
36
class FragmentedSharedBuffer;
37
37
38
class AppHighlightRangeData {
38
class AppHighlightRangeData {
39
WTF_MAKE_FAST_ALLOCATED;
39
WTF_MAKE_FAST_ALLOCATED;
40
public:
40
public:
41
    WEBCORE_EXPORT static std::optional<AppHighlightRangeData> create(const SharedBuffer&);
41
    WEBCORE_EXPORT static std::optional<AppHighlightRangeData> create(const FragmentedSharedBuffer&);
42
    struct NodePathComponent {
42
    struct NodePathComponent {
43
        String identifier;
43
        String identifier;
44
        String nodeName;
44
        String nodeName;
Lines 111-117 public: a/Source/WebCore/Modules/highlight/AppHighlightRangeData.h_sec2
111
    template<class Encoder> void encode(Encoder&) const;
111
    template<class Encoder> void encode(Encoder&) const;
112
    template<class Decoder> static std::optional<AppHighlightRangeData> decode(Decoder&);
112
    template<class Decoder> static std::optional<AppHighlightRangeData> decode(Decoder&);
113
113
114
    Ref<SharedBuffer> toSharedBuffer() const;
114
    Ref<FragmentedSharedBuffer> toSharedBuffer() const;
115
115
116
private:
116
private:
117
    String m_identifier;
117
    String m_identifier;
- a/Source/WebCore/Modules/highlight/AppHighlightStorage.cpp -1 / +1 lines
Lines 237-243 void AppHighlightStorage::storeAppHighlight(Ref<StaticRange>&& range) a/Source/WebCore/Modules/highlight/AppHighlightStorage.cpp_sec1
237
    m_document->page()->chrome().storeAppHighlight(WTFMove(highlight));
237
    m_document->page()->chrome().storeAppHighlight(WTFMove(highlight));
238
}
238
}
239
239
240
void AppHighlightStorage::restoreAndScrollToAppHighlight(Ref<SharedBuffer>&& buffer, ScrollToHighlight scroll)
240
void AppHighlightStorage::restoreAndScrollToAppHighlight(Ref<FragmentedSharedBuffer>&& buffer, ScrollToHighlight scroll)
241
{
241
{
242
    auto appHighlightRangeData = AppHighlightRangeData::create(buffer);
242
    auto appHighlightRangeData = AppHighlightRangeData::create(buffer);
243
    if (!appHighlightRangeData)
243
    if (!appHighlightRangeData)
- a/Source/WebCore/Modules/highlight/AppHighlightStorage.h -2 / +2 lines
Lines 39-45 namespace WebCore { a/Source/WebCore/Modules/highlight/AppHighlightStorage.h_sec1
39
#if ENABLE(APP_HIGHLIGHTS)
39
#if ENABLE(APP_HIGHLIGHTS)
40
40
41
class Document;
41
class Document;
42
class SharedBuffer;
42
class FragmentedSharedBuffer;
43
class StaticRange;
43
class StaticRange;
44
class Highlight;
44
class Highlight;
45
45
Lines 54-60 public: a/Source/WebCore/Modules/highlight/AppHighlightStorage.h_sec2
54
    ~AppHighlightStorage();
54
    ~AppHighlightStorage();
55
55
56
    WEBCORE_EXPORT void storeAppHighlight(Ref<StaticRange>&&);
56
    WEBCORE_EXPORT void storeAppHighlight(Ref<StaticRange>&&);
57
    WEBCORE_EXPORT void restoreAndScrollToAppHighlight(Ref<SharedBuffer>&&, ScrollToHighlight);
57
    WEBCORE_EXPORT void restoreAndScrollToAppHighlight(Ref<FragmentedSharedBuffer>&&, ScrollToHighlight);
58
    void restoreUnrestoredAppHighlights();
58
    void restoreUnrestoredAppHighlights();
59
    MonotonicTime lastRangeSearchTime() const { return m_timeAtLastRangeSearch; }
59
    MonotonicTime lastRangeSearchTime() const { return m_timeAtLastRangeSearch; }
60
    void resetLastRangeSearchTime() { m_timeAtLastRangeSearch = MonotonicTime::now(); }
60
    void resetLastRangeSearchTime() { m_timeAtLastRangeSearch = MonotonicTime::now(); }
- a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBBackingStore.cpp -14 / +14 lines
Lines 686-692 bool SQLiteIDBBackingStore::addExistingIndex(IDBObjectStoreInfo& objectStoreInfo a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBBackingStore.cpp_sec1
686
    SQLiteTransaction transaction(*m_sqliteDB);
686
    SQLiteTransaction transaction(*m_sqliteDB);
687
    transaction.begin();
687
    transaction.begin();
688
688
689
    RefPtr<SharedBuffer> keyPathBlob = serializeIDBKeyPath(info.keyPath());
689
    auto keyPathBlob = serializeIDBKeyPath(info.keyPath());
690
    if (!keyPathBlob) {
690
    if (!keyPathBlob) {
691
        LOG_ERROR("Unable to serialize IDBKeyPath to save in database");
691
        LOG_ERROR("Unable to serialize IDBKeyPath to save in database");
692
        return false;
692
        return false;
Lines 1174-1180 IDBError SQLiteIDBBackingStore::createObjectStore(const IDBResourceIdentifier& t a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBBackingStore.cpp_sec2
1174
        return IDBError { UnknownError, "Attempt to create an object store in a non-version-change transaction"_s };
1174
        return IDBError { UnknownError, "Attempt to create an object store in a non-version-change transaction"_s };
1175
    }
1175
    }
1176
1176
1177
    RefPtr<SharedBuffer> keyPathBlob = serializeIDBKeyPath(info.keyPath());
1177
    auto keyPathBlob = serializeIDBKeyPath(info.keyPath());
1178
    if (!keyPathBlob) {
1178
    if (!keyPathBlob) {
1179
        LOG_ERROR("Unable to serialize IDBKeyPath to save in database for new object store");
1179
        LOG_ERROR("Unable to serialize IDBKeyPath to save in database for new object store");
1180
        return IDBError { UnknownError, "Unable to serialize IDBKeyPath to save in database for new object store"_s };
1180
        return IDBError { UnknownError, "Unable to serialize IDBKeyPath to save in database for new object store"_s };
Lines 1387-1393 IDBError SQLiteIDBBackingStore::createIndex(const IDBResourceIdentifier& transac a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBBackingStore.cpp_sec3
1387
        return IDBError { UnknownError, "Attempt to create an index in a non-version-change transaction"_s };
1387
        return IDBError { UnknownError, "Attempt to create an index in a non-version-change transaction"_s };
1388
    }
1388
    }
1389
1389
1390
    RefPtr<SharedBuffer> keyPathBlob = serializeIDBKeyPath(info.keyPath());
1390
    auto keyPathBlob = serializeIDBKeyPath(info.keyPath());
1391
    if (!keyPathBlob) {
1391
    if (!keyPathBlob) {
1392
        LOG_ERROR("Unable to serialize IDBKeyPath to save in database");
1392
        LOG_ERROR("Unable to serialize IDBKeyPath to save in database");
1393
        return IDBError { UnknownError, "Unable to serialize IDBKeyPath to create index in database"_s };
1393
        return IDBError { UnknownError, "Unable to serialize IDBKeyPath to create index in database"_s };
Lines 1464-1470 IDBError SQLiteIDBBackingStore::uncheckedHasIndexRecord(const IDBIndexInfo& info a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBBackingStore.cpp_sec4
1464
{
1464
{
1465
    hasRecord = false;
1465
    hasRecord = false;
1466
1466
1467
    RefPtr<SharedBuffer> indexKeyBuffer = serializeIDBKeyData(indexKey);
1467
    auto indexKeyBuffer = serializeIDBKeyData(indexKey);
1468
    if (!indexKeyBuffer) {
1468
    if (!indexKeyBuffer) {
1469
        LOG_ERROR("Unable to serialize index key to be stored in the database");
1469
        LOG_ERROR("Unable to serialize index key to be stored in the database");
1470
        return IDBError { UnknownError, "Unable to serialize IDBKey to check for index record in database"_s };
1470
        return IDBError { UnknownError, "Unable to serialize IDBKey to check for index record in database"_s };
Lines 1533-1545 IDBError SQLiteIDBBackingStore::uncheckedPutIndexRecord(int64_t objectStoreID, i a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBBackingStore.cpp_sec5
1533
{
1533
{
1534
    LOG(IndexedDB, "SQLiteIDBBackingStore::uncheckedPutIndexRecord - %s, %s", keyValue.loggingString().utf8().data(), indexKey.loggingString().utf8().data());
1534
    LOG(IndexedDB, "SQLiteIDBBackingStore::uncheckedPutIndexRecord - %s, %s", keyValue.loggingString().utf8().data(), indexKey.loggingString().utf8().data());
1535
1535
1536
    RefPtr<SharedBuffer> indexKeyBuffer = serializeIDBKeyData(indexKey);
1536
    auto indexKeyBuffer = serializeIDBKeyData(indexKey);
1537
    if (!indexKeyBuffer) {
1537
    if (!indexKeyBuffer) {
1538
        LOG_ERROR("Unable to serialize index key to be stored in the database");
1538
        LOG_ERROR("Unable to serialize index key to be stored in the database");
1539
        return IDBError { UnknownError, "Unable to serialize index key to be stored in the database"_s };
1539
        return IDBError { UnknownError, "Unable to serialize index key to be stored in the database"_s };
1540
    }
1540
    }
1541
1541
1542
    RefPtr<SharedBuffer> valueBuffer = serializeIDBKeyData(keyValue);
1542
    auto valueBuffer = serializeIDBKeyData(keyValue);
1543
    if (!valueBuffer) {
1543
    if (!valueBuffer) {
1544
        LOG_ERROR("Unable to serialize the value to be stored in the database");
1544
        LOG_ERROR("Unable to serialize the value to be stored in the database");
1545
        return IDBError { UnknownError, "Unable to serialize value to be stored in the database"_s };
1545
        return IDBError { UnknownError, "Unable to serialize value to be stored in the database"_s };
Lines 1661-1667 IDBError SQLiteIDBBackingStore::keyExistsInObjectStore(const IDBResourceIdentifi a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBBackingStore.cpp_sec6
1661
    if (!transaction || !transaction->inProgress())
1661
    if (!transaction || !transaction->inProgress())
1662
        return IDBError { UnknownError, "Attempt to see if key exists in objectstore without an in-progress transaction"_s };
1662
        return IDBError { UnknownError, "Attempt to see if key exists in objectstore without an in-progress transaction"_s };
1663
1663
1664
    RefPtr<SharedBuffer> keyBuffer = serializeIDBKeyData(keyData);
1664
    auto keyBuffer = serializeIDBKeyData(keyData);
1665
    if (!keyBuffer) {
1665
    if (!keyBuffer) {
1666
        LOG_ERROR("Unable to serialize IDBKey to check for existence in object store");
1666
        LOG_ERROR("Unable to serialize IDBKey to check for existence in object store");
1667
        return IDBError { UnknownError, "Unable to serialize IDBKey to check for existence in object store"_s };
1667
        return IDBError { UnknownError, "Unable to serialize IDBKey to check for existence in object store"_s };
Lines 1741-1747 IDBError SQLiteIDBBackingStore::deleteRecord(SQLiteIDBTransaction& transaction, a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBBackingStore.cpp_sec7
1741
    ASSERT(transaction.mode() != IDBTransactionMode::Readonly);
1741
    ASSERT(transaction.mode() != IDBTransactionMode::Readonly);
1742
    UNUSED_PARAM(transaction);
1742
    UNUSED_PARAM(transaction);
1743
1743
1744
    RefPtr<SharedBuffer> keyBuffer = serializeIDBKeyData(keyData);
1744
    auto keyBuffer = serializeIDBKeyData(keyData);
1745
    if (!keyBuffer) {
1745
    if (!keyBuffer) {
1746
        LOG_ERROR("Unable to serialize IDBKeyData to be removed from the database");
1746
        LOG_ERROR("Unable to serialize IDBKeyData to be removed from the database");
1747
        return IDBError { UnknownError, "Unable to serialize IDBKeyData to be removed from the database"_s };
1747
        return IDBError { UnknownError, "Unable to serialize IDBKeyData to be removed from the database"_s };
Lines 1962-1968 IDBError SQLiteIDBBackingStore::addRecord(const IDBResourceIdentifier& transacti a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBBackingStore.cpp_sec8
1962
        return IDBError { UnknownError, "Attempt to store a record in an object store in a read-only transaction"_s };
1962
        return IDBError { UnknownError, "Attempt to store a record in an object store in a read-only transaction"_s };
1963
    }
1963
    }
1964
1964
1965
    RefPtr<SharedBuffer> keyBuffer = serializeIDBKeyData(keyData);
1965
    auto keyBuffer = serializeIDBKeyData(keyData);
1966
    if (!keyBuffer) {
1966
    if (!keyBuffer) {
1967
        LOG_ERROR("Unable to serialize IDBKey to be stored in an object store");
1967
        LOG_ERROR("Unable to serialize IDBKey to be stored in an object store");
1968
        return IDBError { UnknownError, "Unable to serialize IDBKey to be stored in an object store"_s };
1968
        return IDBError { UnknownError, "Unable to serialize IDBKey to be stored in an object store"_s };
Lines 2124-2130 IDBError SQLiteIDBBackingStore::getRecord(const IDBResourceIdentifier& transacti a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBBackingStore.cpp_sec9
2124
    auto key = keyRange.lowerKey;
2124
    auto key = keyRange.lowerKey;
2125
    if (key.isNull())
2125
    if (key.isNull())
2126
        key = IDBKeyData::minimum();
2126
        key = IDBKeyData::minimum();
2127
    RefPtr<SharedBuffer> lowerBuffer = serializeIDBKeyData(key);
2127
    auto lowerBuffer = serializeIDBKeyData(key);
2128
    if (!lowerBuffer) {
2128
    if (!lowerBuffer) {
2129
        LOG_ERROR("Unable to serialize lower IDBKey in lookup range");
2129
        LOG_ERROR("Unable to serialize lower IDBKey in lookup range");
2130
        return IDBError { UnknownError, "Unable to serialize lower IDBKey in lookup range"_s };
2130
        return IDBError { UnknownError, "Unable to serialize lower IDBKey in lookup range"_s };
Lines 2133-2139 IDBError SQLiteIDBBackingStore::getRecord(const IDBResourceIdentifier& transacti a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBBackingStore.cpp_sec10
2133
    key = keyRange.upperKey;
2133
    key = keyRange.upperKey;
2134
    if (key.isNull())
2134
    if (key.isNull())
2135
        key = IDBKeyData::maximum();
2135
        key = IDBKeyData::maximum();
2136
    RefPtr<SharedBuffer> upperBuffer = serializeIDBKeyData(key);
2136
    auto upperBuffer = serializeIDBKeyData(key);
2137
    if (!upperBuffer) {
2137
    if (!upperBuffer) {
2138
        LOG_ERROR("Unable to serialize upper IDBKey in lookup range");
2138
        LOG_ERROR("Unable to serialize upper IDBKey in lookup range");
2139
        return IDBError { UnknownError, "Unable to serialize upper IDBKey in lookup range"_s };
2139
        return IDBError { UnknownError, "Unable to serialize upper IDBKey in lookup range"_s };
Lines 2443-2449 IDBError SQLiteIDBBackingStore::uncheckedGetIndexRecordForOneKey(int64_t indexID a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBBackingStore.cpp_sec11
2443
2443
2444
    ASSERT(key.isValid() && key.type() != IndexedDB::KeyType::Max && key.type() != IndexedDB::KeyType::Min);
2444
    ASSERT(key.isValid() && key.type() != IndexedDB::KeyType::Max && key.type() != IndexedDB::KeyType::Min);
2445
2445
2446
    RefPtr<SharedBuffer> buffer = serializeIDBKeyData(key);
2446
    auto buffer = serializeIDBKeyData(key);
2447
    if (!buffer) {
2447
    if (!buffer) {
2448
        LOG_ERROR("Unable to serialize IDBKey to look up one index record");
2448
        LOG_ERROR("Unable to serialize IDBKey to look up one index record");
2449
        return IDBError { UnknownError, "Unable to serialize IDBKey to look up one index record"_s };
2449
        return IDBError { UnknownError, "Unable to serialize IDBKey to look up one index record"_s };
Lines 2508-2521 IDBError SQLiteIDBBackingStore::getCount(const IDBResourceIdentifier& transactio a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBBackingStore.cpp_sec12
2508
    outCount = 0;
2508
    outCount = 0;
2509
2509
2510
    auto lowerKey = range.lowerKey.isNull() ? IDBKeyData::minimum() : range.lowerKey;
2510
    auto lowerKey = range.lowerKey.isNull() ? IDBKeyData::minimum() : range.lowerKey;
2511
    RefPtr<SharedBuffer> lowerBuffer = serializeIDBKeyData(lowerKey);
2511
    auto lowerBuffer = serializeIDBKeyData(lowerKey);
2512
    if (!lowerBuffer) {
2512
    if (!lowerBuffer) {
2513
        LOG_ERROR("Unable to serialize lower IDBKey in lookup range");
2513
        LOG_ERROR("Unable to serialize lower IDBKey in lookup range");
2514
        return IDBError { UnknownError, "Unable to serialize lower IDBKey in lookup range for count operation"_s };
2514
        return IDBError { UnknownError, "Unable to serialize lower IDBKey in lookup range for count operation"_s };
2515
    }
2515
    }
2516
2516
2517
    auto upperKey = range.upperKey.isNull() ? IDBKeyData::maximum() : range.upperKey;
2517
    auto upperKey = range.upperKey.isNull() ? IDBKeyData::maximum() : range.upperKey;
2518
    RefPtr<SharedBuffer> upperBuffer = serializeIDBKeyData(upperKey);
2518
    auto upperBuffer = serializeIDBKeyData(upperKey);
2519
    if (!upperBuffer) {
2519
    if (!upperBuffer) {
2520
        LOG_ERROR("Unable to serialize upper IDBKey in lookup range");
2520
        LOG_ERROR("Unable to serialize upper IDBKey in lookup range");
2521
        return IDBError { UnknownError, "Unable to serialize upper IDBKey in lookup range for count operation"_s };
2521
        return IDBError { UnknownError, "Unable to serialize upper IDBKey in lookup range for count operation"_s };
- a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBCursor.cpp -2 / +2 lines
Lines 269-275 bool SQLiteIDBCursor::bindArguments() a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBCursor.cpp_sec1
269
        return false;
269
        return false;
270
    }
270
    }
271
271
272
    RefPtr<SharedBuffer> buffer = serializeIDBKeyData(m_currentLowerKey);
272
    auto buffer = serializeIDBKeyData(m_currentLowerKey);
273
    if (m_statement->bindBlob(currentBindArgument++, *buffer) != SQLITE_OK) {
273
    if (m_statement->bindBlob(currentBindArgument++, *buffer) != SQLITE_OK) {
274
        LOG_ERROR("Could not create cursor statement (lower key)");
274
        LOG_ERROR("Could not create cursor statement (lower key)");
275
        return false;
275
        return false;
Lines 315-321 bool SQLiteIDBCursor::resetAndRebindPreIndexStatementIfNecessary() a/Source/WebCore/Modules/indexeddb/server/SQLiteIDBCursor.cpp_sec2
315
        return false;
315
        return false;
316
    }
316
    }
317
317
318
    RefPtr<SharedBuffer> buffer = serializeIDBKeyData(key);
318
    auto buffer = serializeIDBKeyData(key);
319
    if (m_preIndexStatement->bindBlob(currentBindArgument++, *buffer) != SQLITE_OK) {
319
    if (m_preIndexStatement->bindBlob(currentBindArgument++, *buffer) != SQLITE_OK) {
320
        LOG_ERROR("Could not bind id argument to pre statement (key)");
320
        LOG_ERROR("Could not bind id argument to pre statement (key)");
321
        return false;
321
        return false;
- a/Source/WebCore/Modules/mediarecorder/MediaRecorder.cpp -1 / +1 lines
Lines 196-202 ExceptionOr<void> MediaRecorder::startRecording(std::optional<unsigned> timeSlic a/Source/WebCore/Modules/mediarecorder/MediaRecorder.cpp_sec1
196
    return { };
196
    return { };
197
}
197
}
198
198
199
static inline Ref<BlobEvent> createDataAvailableEvent(ScriptExecutionContext* context, RefPtr<SharedBuffer>&& buffer, const String& mimeType, double timeCode)
199
static inline Ref<BlobEvent> createDataAvailableEvent(ScriptExecutionContext* context, RefPtr<FragmentedSharedBuffer>&& buffer, const String& mimeType, double timeCode)
200
{
200
{
201
    auto blob = buffer ? Blob::create(context, buffer->extractData(), mimeType) : Blob::create(context);
201
    auto blob = buffer ? Blob::create(context, buffer->extractData(), mimeType) : Blob::create(context);
202
    return BlobEvent::create(eventNames().dataavailableEvent, BlobEvent::Init { { false, false, false }, WTFMove(blob), timeCode }, BlobEvent::IsTrusted::Yes);
202
    return BlobEvent::create(eventNames().dataavailableEvent, BlobEvent::Init { { false, false, false }, WTFMove(blob), timeCode }, BlobEvent::IsTrusted::Yes);
- a/Source/WebCore/Modules/mediarecorder/MediaRecorder.h -1 / +1 lines
Lines 103-109 private: a/Source/WebCore/Modules/mediarecorder/MediaRecorder.h_sec1
103
    void dispatchError(Exception&&);
103
    void dispatchError(Exception&&);
104
104
105
    enum class TakePrivateRecorder { No, Yes };
105
    enum class TakePrivateRecorder { No, Yes };
106
    using FetchDataCallback = Function<void(RefPtr<SharedBuffer>&&, const String& mimeType, double)>;
106
    using FetchDataCallback = Function<void(RefPtr<FragmentedSharedBuffer>&&, const String& mimeType, double)>;
107
    void fetchData(FetchDataCallback&&, TakePrivateRecorder);
107
    void fetchData(FetchDataCallback&&, TakePrivateRecorder);
108
108
109
    // MediaStream::Observer
109
    // MediaStream::Observer
- a/Source/WebCore/Modules/mediasession/MediaMetadata.cpp -1 / +1 lines
Lines 77-83 void ArtworkImageLoader::notifyFinished(CachedResource& resource, const NetworkL a/Source/WebCore/Modules/mediasession/MediaMetadata.cpp_sec1
77
        return;
77
        return;
78
    }
78
    }
79
    // Sanitize the image by decoding it into a BitmapImage.
79
    // Sanitize the image by decoding it into a BitmapImage.
80
    RefPtr<SharedBuffer> bufferToSanitize = m_cachedImage->image()->data();
80
    RefPtr<FragmentedSharedBuffer> bufferToSanitize = m_cachedImage->image()->data();
81
    auto bitmapImage = BitmapImage::create();
81
    auto bitmapImage = BitmapImage::create();
82
    bitmapImage->setData(WTFMove(bufferToSanitize), true);
82
    bitmapImage->setData(WTFMove(bufferToSanitize), true);
83
    auto imageBuffer = ImageBuffer::create(bitmapImage->size(), RenderingMode::Unaccelerated, 1, DestinationColorSpace::SRGB(), PixelFormat::BGRA8);
83
    auto imageBuffer = ImageBuffer::create(bitmapImage->size(), RenderingMode::Unaccelerated, 1, DestinationColorSpace::SRGB(), PixelFormat::BGRA8);
- a/Source/WebCore/Modules/mediastream/RTCDataChannelRemoteHandler.cpp -1 / +1 lines
Lines 82-88 void RTCDataChannelRemoteHandler::readyToSend() a/Source/WebCore/Modules/mediastream/RTCDataChannelRemoteHandler.cpp_sec1
82
    m_isReadyToSend = true;
82
    m_isReadyToSend = true;
83
83
84
    for (auto& message : m_pendingMessages)
84
    for (auto& message : m_pendingMessages)
85
        m_connection->sendData(m_remoteIdentifier, message.isRaw, message.buffer->data(), message.buffer->size());
85
        m_connection->sendData(m_remoteIdentifier, message.isRaw, message.buffer->makeContiguous()->data(), message.buffer->size());
86
    m_pendingMessages.clear();
86
    m_pendingMessages.clear();
87
87
88
    if (m_isPendingClose)
88
    if (m_isPendingClose)
- a/Source/WebCore/Modules/mediastream/RTCDataChannelRemoteHandler.h -2 / +2 lines
Lines 39-45 namespace WebCore { a/Source/WebCore/Modules/mediastream/RTCDataChannelRemoteHandler.h_sec1
39
class RTCDataChannelHandlerClient;
39
class RTCDataChannelHandlerClient;
40
class RTCDataChannelRemoteHandlerConnection;
40
class RTCDataChannelRemoteHandlerConnection;
41
class RTCError;
41
class RTCError;
42
class SharedBuffer;
42
class FragmentedSharedBuffer;
43
43
44
class RTCDataChannelRemoteHandler final : public RTCDataChannelHandler, public CanMakeWeakPtr<RTCDataChannelRemoteHandler> {
44
class RTCDataChannelRemoteHandler final : public RTCDataChannelHandler, public CanMakeWeakPtr<RTCDataChannelRemoteHandler> {
45
    WTF_MAKE_FAST_ALLOCATED;
45
    WTF_MAKE_FAST_ALLOCATED;
Lines 73-79 private: a/Source/WebCore/Modules/mediastream/RTCDataChannelRemoteHandler.h_sec2
73
73
74
    struct Message {
74
    struct Message {
75
        bool isRaw { false };
75
        bool isRaw { false };
76
        Ref<SharedBuffer> buffer;
76
        Ref<FragmentedSharedBuffer> buffer;
77
    };
77
    };
78
    Vector<Message> m_pendingMessages;
78
    Vector<Message> m_pendingMessages;
79
    bool m_isPendingClose { false };
79
    bool m_isPendingClose { false };
- a/Source/WebCore/Modules/mediastream/libwebrtc/LibWebRTCDataChannelHandler.cpp -2 / +2 lines
Lines 97-104 void LibWebRTCDataChannelHandler::setClient(RTCDataChannelHandlerClient& client, a/Source/WebCore/Modules/mediastream/libwebrtc/LibWebRTCDataChannelHandler.cpp_sec1
97
    m_contextIdentifier = contextIdentifier;
97
    m_contextIdentifier = contextIdentifier;
98
98
99
    for (auto& message : m_bufferedMessages) {
99
    for (auto& message : m_bufferedMessages) {
100
        switchOn(message, [&](Ref<SharedBuffer>& data) {
100
        switchOn(message, [&](Ref<FragmentedSharedBuffer>& data) {
101
            client.didReceiveRawData(data->data(), data->size());
101
            client.didReceiveRawData(data->makeContiguous()->data(), data->size());
102
        }, [&](String& text) {
102
        }, [&](String& text) {
103
            client.didReceiveStringData(text);
103
            client.didReceiveStringData(text);
104
        }, [&](StateChange stateChange) {
104
        }, [&](StateChange stateChange) {
- a/Source/WebCore/Modules/mediastream/libwebrtc/LibWebRTCDataChannelHandler.h -1 / +1 lines
Lines 82-88 private: a/Source/WebCore/Modules/mediastream/libwebrtc/LibWebRTCDataChannelHandler.h_sec1
82
        RTCDataChannelState state;
82
        RTCDataChannelState state;
83
        std::optional<webrtc::RTCError> error;
83
        std::optional<webrtc::RTCError> error;
84
    };
84
    };
85
    using Message = std::variant<StateChange, String, Ref<SharedBuffer>>;
85
    using Message = std::variant<StateChange, String, Ref<FragmentedSharedBuffer>>;
86
    using PendingMessages = Vector<Message>;
86
    using PendingMessages = Vector<Message>;
87
    void storeMessage(PendingMessages&, const webrtc::DataBuffer&);
87
    void storeMessage(PendingMessages&, const webrtc::DataBuffer&);
88
    void processMessage(const webrtc::DataBuffer&);
88
    void processMessage(const webrtc::DataBuffer&);
- a/Source/WebCore/Modules/model-element/HTMLModelElement.cpp -6 / +5 lines
Lines 116-122 void HTMLModelElement::setSourceURL(const URL& url) a/Source/WebCore/Modules/model-element/HTMLModelElement.cpp_sec1
116
116
117
    m_sourceURL = url;
117
    m_sourceURL = url;
118
118
119
    m_data = nullptr;
119
    m_data.reset();
120
    m_dataComplete = false;
120
    m_dataComplete = false;
121
121
122
    if (m_resource) {
122
    if (m_resource) {
Lines 149-155 void HTMLModelElement::setSourceURL(const URL& url) a/Source/WebCore/Modules/model-element/HTMLModelElement.cpp_sec2
149
        return;
149
        return;
150
    }
150
    }
151
151
152
    m_data = SharedBuffer::create();
152
    m_data.empty();
153
153
154
    m_resource = resource.value();
154
    m_resource = resource.value();
155
    m_resource->addClient(*this);
155
    m_resource->addClient(*this);
Lines 180-187 RenderPtr<RenderElement> HTMLModelElement::createElementRenderer(RenderStyle&& s a/Source/WebCore/Modules/model-element/HTMLModelElement.cpp_sec3
180
void HTMLModelElement::dataReceived(CachedResource& resource, const uint8_t* data, int dataLength)
180
void HTMLModelElement::dataReceived(CachedResource& resource, const uint8_t* data, int dataLength)
181
{
181
{
182
    ASSERT_UNUSED(resource, &resource == m_resource);
182
    ASSERT_UNUSED(resource, &resource == m_resource);
183
    ASSERT(m_data);
183
    m_data.append(data, dataLength);
184
    m_data->append(data, dataLength);
185
}
184
}
186
185
187
void HTMLModelElement::notifyFinished(CachedResource& resource, const NetworkLoadMetrics&)
186
void HTMLModelElement::notifyFinished(CachedResource& resource, const NetworkLoadMetrics&)
Lines 195-201 void HTMLModelElement::notifyFinished(CachedResource& resource, const NetworkLoa a/Source/WebCore/Modules/model-element/HTMLModelElement.cpp_sec4
195
    };
194
    };
196
195
197
    if (resource.loadFailedOrCanceled()) {
196
    if (resource.loadFailedOrCanceled()) {
198
        m_data = nullptr;
197
        m_data.reset();
199
198
200
        invalidateResourceHandleAndUpdateRenderer();
199
        invalidateResourceHandleAndUpdateRenderer();
201
200
Lines 204-210 void HTMLModelElement::notifyFinished(CachedResource& resource, const NetworkLoa a/Source/WebCore/Modules/model-element/HTMLModelElement.cpp_sec5
204
    }
203
    }
205
204
206
    m_dataComplete = true;
205
    m_dataComplete = true;
207
    m_model = Model::create(m_data.releaseNonNull().get(), resource.mimeType(), resource.url());
206
    m_model = Model::create(m_data.take()->makeContiguous().get(), resource.mimeType(), resource.url());
208
207
209
    invalidateResourceHandleAndUpdateRenderer();
208
    invalidateResourceHandleAndUpdateRenderer();
210
209
- a/Source/WebCore/Modules/model-element/HTMLModelElement.h -1 / +1 lines
Lines 133-139 private: a/Source/WebCore/Modules/model-element/HTMLModelElement.h_sec1
133
133
134
    URL m_sourceURL;
134
    URL m_sourceURL;
135
    CachedResourceHandle<CachedRawResource> m_resource;
135
    CachedResourceHandle<CachedRawResource> m_resource;
136
    RefPtr<SharedBuffer> m_data;
136
    SharedBufferBuilder m_data;
137
    RefPtr<Model> m_model;
137
    RefPtr<Model> m_model;
138
    UniqueRef<ReadyPromise> m_readyPromise;
138
    UniqueRef<ReadyPromise> m_readyPromise;
139
    bool m_dataComplete { false };
139
    bool m_dataComplete { false };
- a/Source/WebCore/Modules/model-element/scenekit/SceneKitModelLoaderUSD.mm -1 / +1 lines
Lines 104-110 static RetainPtr<NSURL> writeToTemporaryFile(WebCore::Model& modelSource) a/Source/WebCore/Modules/model-element/scenekit/SceneKitModelLoaderUSD.mm_sec1
104
    auto filePath = FileSystem::openTemporaryFile("ModelFile", fileHandle, ".usdz");
104
    auto filePath = FileSystem::openTemporaryFile("ModelFile", fileHandle, ".usdz");
105
    ASSERT(FileSystem::isHandleValid(fileHandle));
105
    ASSERT(FileSystem::isHandleValid(fileHandle));
106
106
107
    size_t byteCount = FileSystem::writeToFile(fileHandle, modelSource.data()->data(), modelSource.data()->size());
107
    size_t byteCount = FileSystem::writeToFile(fileHandle, modelSource.data()->makeContiguous()->data(), modelSource.data()->size());
108
    ASSERT_UNUSED(byteCount, byteCount == modelSource.data()->size());
108
    ASSERT_UNUSED(byteCount, byteCount == modelSource.data()->size());
109
    FileSystem::closeFile(fileHandle);
109
    FileSystem::closeFile(fileHandle);
110
110
- a/Source/WebCore/Modules/streams/ReadableStreamSink.h -1 / +1 lines
Lines 35-41 namespace WebCore { a/Source/WebCore/Modules/streams/ReadableStreamSink.h_sec1
35
35
36
class BufferSource;
36
class BufferSource;
37
class ReadableStream;
37
class ReadableStream;
38
class SharedBuffer;
38
class FragmentedSharedBuffer;
39
39
40
class ReadableStreamSink : public RefCounted<ReadableStreamSink> {
40
class ReadableStreamSink : public RefCounted<ReadableStreamSink> {
41
public:
41
public:
- a/Source/WebCore/bindings/js/ScriptBufferSourceProvider.h -3 / +7 lines
Lines 51-63 public: a/Source/WebCore/bindings/js/ScriptBufferSourceProvider.h_sec1
51
        if (m_scriptBuffer.isEmpty())
51
        if (m_scriptBuffer.isEmpty())
52
            return emptyString();
52
            return emptyString();
53
53
54
        if (!m_contiguousBuffer && (!m_containsOnlyASCII || *m_containsOnlyASCII))
55
            m_contiguousBuffer = m_scriptBuffer.buffer()->makeContiguous();
54
        if (!m_containsOnlyASCII) {
56
        if (!m_containsOnlyASCII) {
55
            m_containsOnlyASCII = charactersAreAllASCII(m_scriptBuffer.buffer()->data(), m_scriptBuffer.buffer()->size());
57
            m_containsOnlyASCII = charactersAreAllASCII(m_contiguousBuffer->data(), m_scriptBuffer.buffer()->size());
56
            if (*m_containsOnlyASCII)
58
            if (*m_containsOnlyASCII)
57
                m_scriptHash = StringHasher::computeHashAndMaskTop8Bits(m_scriptBuffer.buffer()->data(), m_scriptBuffer.buffer()->size());
59
                m_scriptHash = StringHasher::computeHashAndMaskTop8Bits(m_contiguousBuffer->data(), m_scriptBuffer.buffer()->size());
58
        }
60
        }
59
        if (*m_containsOnlyASCII)
61
        if (*m_containsOnlyASCII)
60
            return { m_scriptBuffer.buffer()->data(), static_cast<unsigned>(m_scriptBuffer.buffer()->size()) };
62
            return { m_contiguousBuffer->data(), static_cast<unsigned>(m_scriptBuffer.buffer()->size()) };
61
63
62
        if (!m_cachedScriptString) {
64
        if (!m_cachedScriptString) {
63
            m_cachedScriptString = m_scriptBuffer.toString();
65
            m_cachedScriptString = m_scriptBuffer.toString();
Lines 81-86 public: a/Source/WebCore/bindings/js/ScriptBufferSourceProvider.h_sec2
81
            return;
83
            return;
82
84
83
        m_scriptBuffer = scriptBuffer;
85
        m_scriptBuffer = scriptBuffer;
86
        m_contiguousBuffer = nullptr;
84
    }
87
    }
85
88
86
private:
89
private:
Lines 91-96 private: a/Source/WebCore/bindings/js/ScriptBufferSourceProvider.h_sec3
91
    }
94
    }
92
95
93
    ScriptBuffer m_scriptBuffer;
96
    ScriptBuffer m_scriptBuffer;
97
    mutable RefPtr<SharedBuffer> m_contiguousBuffer;
94
    mutable unsigned m_scriptHash { 0 };
98
    mutable unsigned m_scriptHash { 0 };
95
    mutable String m_cachedScriptString;
99
    mutable String m_cachedScriptString;
96
    mutable std::optional<bool> m_containsOnlyASCII;
100
    mutable std::optional<bool> m_containsOnlyASCII;
- a/Source/WebCore/bindings/js/SerializedScriptValue.h -1 / +1 lines
Lines 55-61 class DetachedOffscreenCanvas; a/Source/WebCore/bindings/js/SerializedScriptValue.h_sec1
55
class IDBValue;
55
class IDBValue;
56
class MessagePort;
56
class MessagePort;
57
class ImageBitmapBacking;
57
class ImageBitmapBacking;
58
class SharedBuffer;
58
class FragmentedSharedBuffer;
59
enum class SerializationReturnCode;
59
enum class SerializationReturnCode;
60
60
61
enum class SerializationErrorMode { NonThrowing, Throwing };
61
enum class SerializationErrorMode { NonThrowing, Throwing };
- a/Source/WebCore/css/CSSFontFaceSource.h -1 / +1 lines
Lines 34-39 namespace WebCore { a/Source/WebCore/css/CSSFontFaceSource.h_sec1
34
34
35
class CSSFontFace;
35
class CSSFontFace;
36
class CSSFontSelector;
36
class CSSFontSelector;
37
class SharedBuffer;
37
class Document;
38
class Document;
38
class Font;
39
class Font;
39
class FontCreationContext;
40
class FontCreationContext;
Lines 42-48 class FontDescription; a/Source/WebCore/css/CSSFontFaceSource.h_sec2
42
struct FontSelectionSpecifiedCapabilities;
43
struct FontSelectionSpecifiedCapabilities;
43
struct FontVariantSettings;
44
struct FontVariantSettings;
44
class SVGFontFaceElement;
45
class SVGFontFaceElement;
45
class SharedBuffer;
46
46
47
template <typename T> class FontTaggedSettings;
47
template <typename T> class FontTaggedSettings;
48
typedef FontTaggedSettings<int> FontFeatureSettings;
48
typedef FontTaggedSettings<int> FontFeatureSettings;
- a/Source/WebCore/dom/DataTransfer.cpp -1 / +1 lines
Lines 402-408 struct PasteboardFileTypeReader final : PasteboardFileReader { a/Source/WebCore/dom/DataTransfer.cpp_sec1
402
        types.add(File::contentTypeForFile(filename));
402
        types.add(File::contentTypeForFile(filename));
403
    }
403
    }
404
404
405
    void readBuffer(const String&, const String& type, Ref<SharedBuffer>&&)
405
    void readBuffer(const String&, const String& type, Ref<FragmentedSharedBuffer>&&)
406
    {
406
    {
407
        types.add(type);
407
        types.add(type);
408
    }
408
    }
- a/Source/WebCore/editing/Editor.cpp -1 / +1 lines
Lines 4133-4139 PromisedAttachmentInfo Editor::promisedAttachmentInfo(Element& element) a/Source/WebCore/editing/Editor.cpp_sec1
4133
    return { attachment->uniqueIdentifier(), WTFMove(additionalTypes), WTFMove(additionalData) };
4133
    return { attachment->uniqueIdentifier(), WTFMove(additionalTypes), WTFMove(additionalData) };
4134
}
4134
}
4135
4135
4136
void Editor::registerAttachmentIdentifier(const String& identifier, const String& contentType, const String& preferredFileName, Ref<SharedBuffer>&& data)
4136
void Editor::registerAttachmentIdentifier(const String& identifier, const String& contentType, const String& preferredFileName, Ref<FragmentedSharedBuffer>&& data)
4137
{
4137
{
4138
    if (auto* client = this->client())
4138
    if (auto* client = this->client())
4139
        client->registerAttachmentIdentifier(identifier, contentType, preferredFileName, WTFMove(data));
4139
        client->registerAttachmentIdentifier(identifier, contentType, preferredFileName, WTFMove(data));
- a/Source/WebCore/editing/Editor.h -3 / +4 lines
Lines 57-65 namespace WebCore { a/Source/WebCore/editing/Editor.h_sec1
57
57
58
class AlternativeTextController;
58
class AlternativeTextController;
59
class ArchiveResource;
59
class ArchiveResource;
60
class DataTransfer;
61
class CompositeEditCommand;
60
class CompositeEditCommand;
61
class SharedBuffer;
62
class CustomUndoStep;
62
class CustomUndoStep;
63
class DataTransfer;
63
class DeleteButtonController;
64
class DeleteButtonController;
64
class EditCommand;
65
class EditCommand;
65
class EditCommandComposition;
66
class EditCommandComposition;
Lines 74-80 class KillRing; a/Source/WebCore/editing/Editor.h_sec2
74
class Pasteboard;
75
class Pasteboard;
75
class PasteboardWriterData;
76
class PasteboardWriterData;
76
class RenderLayer;
77
class RenderLayer;
77
class SharedBuffer;
78
class FragmentedSharedBuffer;
78
class Font;
79
class Font;
79
class SpellCheckRequest;
80
class SpellCheckRequest;
80
class SpellChecker;
81
class SpellChecker;
Lines 563-569 public: a/Source/WebCore/editing/Editor.h_sec3
563
564
564
#if ENABLE(ATTACHMENT_ELEMENT)
565
#if ENABLE(ATTACHMENT_ELEMENT)
565
    WEBCORE_EXPORT void insertAttachment(const String& identifier, std::optional<uint64_t>&& fileSize, const String& fileName, const String& contentType);
566
    WEBCORE_EXPORT void insertAttachment(const String& identifier, std::optional<uint64_t>&& fileSize, const String& fileName, const String& contentType);
566
    void registerAttachmentIdentifier(const String&, const String& contentType, const String& preferredFileName, Ref<SharedBuffer>&& fileData);
567
    void registerAttachmentIdentifier(const String&, const String& contentType, const String& preferredFileName, Ref<FragmentedSharedBuffer>&& fileData);
567
    void registerAttachments(Vector<SerializedAttachmentData>&&);
568
    void registerAttachments(Vector<SerializedAttachmentData>&&);
568
    void registerAttachmentIdentifier(const String&, const String& contentType, const String& filePath);
569
    void registerAttachmentIdentifier(const String&, const String& contentType, const String& filePath);
569
    void registerAttachmentIdentifier(const String&);
570
    void registerAttachmentIdentifier(const String&);
- a/Source/WebCore/editing/WebContentReader.h -10 / +10 lines
Lines 72-87 private: a/Source/WebCore/editing/WebContentReader.h_sec1
72
    bool readFilePath(const String&, PresentationSize preferredPresentationSize = { }, const String& contentType = { }) override;
72
    bool readFilePath(const String&, PresentationSize preferredPresentationSize = { }, const String& contentType = { }) override;
73
    bool readFilePaths(const Vector<String>&) override;
73
    bool readFilePaths(const Vector<String>&) override;
74
    bool readHTML(const String&) override;
74
    bool readHTML(const String&) override;
75
    bool readImage(Ref<SharedBuffer>&&, const String& type, PresentationSize preferredPresentationSize = { }) override;
75
    bool readImage(Ref<FragmentedSharedBuffer>&&, const String& type, PresentationSize preferredPresentationSize = { }) override;
76
    bool readURL(const URL&, const String& title) override;
76
    bool readURL(const URL&, const String& title) override;
77
    bool readPlainText(const String&) override;
77
    bool readPlainText(const String&) override;
78
#endif
78
#endif
79
79
80
#if PLATFORM(COCOA)
80
#if PLATFORM(COCOA)
81
    bool readWebArchive(SharedBuffer&) override;
81
    bool readWebArchive(FragmentedSharedBuffer&) override;
82
    bool readRTFD(SharedBuffer&) override;
82
    bool readRTFD(FragmentedSharedBuffer&) override;
83
    bool readRTF(SharedBuffer&) override;
83
    bool readRTF(FragmentedSharedBuffer&) override;
84
    bool readDataBuffer(SharedBuffer&, const String& type, const String& name, PresentationSize preferredPresentationSize = { }) override;
84
    bool readDataBuffer(FragmentedSharedBuffer&, const String& type, const String& name, PresentationSize preferredPresentationSize = { }) override;
85
#endif
85
#endif
86
};
86
};
87
87
Lines 99-114 private: a/Source/WebCore/editing/WebContentReader.h_sec2
99
    bool readFilePath(const String&, PresentationSize = { }, const String& = { }) override { return false; }
99
    bool readFilePath(const String&, PresentationSize = { }, const String& = { }) override { return false; }
100
    bool readFilePaths(const Vector<String>&) override { return false; }
100
    bool readFilePaths(const Vector<String>&) override { return false; }
101
    bool readHTML(const String&) override;
101
    bool readHTML(const String&) override;
102
    bool readImage(Ref<SharedBuffer>&&, const String&, PresentationSize = { }) override { return false; }
102
    bool readImage(Ref<FragmentedSharedBuffer>&&, const String&, PresentationSize = { }) override { return false; }
103
    bool readURL(const URL&, const String&) override { return false; }
103
    bool readURL(const URL&, const String&) override { return false; }
104
    bool readPlainText(const String&) override { return false; }
104
    bool readPlainText(const String&) override { return false; }
105
#endif
105
#endif
106
106
107
#if PLATFORM(COCOA)
107
#if PLATFORM(COCOA)
108
    bool readWebArchive(SharedBuffer&) override;
108
    bool readWebArchive(FragmentedSharedBuffer&) override;
109
    bool readRTFD(SharedBuffer&) override;
109
    bool readRTFD(FragmentedSharedBuffer&) override;
110
    bool readRTF(SharedBuffer&) override;
110
    bool readRTF(FragmentedSharedBuffer&) override;
111
    bool readDataBuffer(SharedBuffer&, const String&, const String&, PresentationSize = { }) override { return false; }
111
    bool readDataBuffer(FragmentedSharedBuffer&, const String&, const String&, PresentationSize = { }) override { return false; }
112
#endif
112
#endif
113
};
113
};
114
114
- a/Source/WebCore/editing/WebCorePasteboardFileReader.cpp -1 / +1 lines
Lines 39-45 void WebCorePasteboardFileReader::readFilename(const String& filename) a/Source/WebCore/editing/WebCorePasteboardFileReader.cpp_sec1
39
    files.append(File::create(context.get(), filename));
39
    files.append(File::create(context.get(), filename));
40
}
40
}
41
41
42
void WebCorePasteboardFileReader::readBuffer(const String& filename, const String& type, Ref<SharedBuffer>&& buffer)
42
void WebCorePasteboardFileReader::readBuffer(const String& filename, const String& type, Ref<FragmentedSharedBuffer>&& buffer)
43
{
43
{
44
    files.append(File::create(context.get(), Blob::create(context.get(), buffer->extractData(), type), filename));
44
    files.append(File::create(context.get(), Blob::create(context.get(), buffer->extractData(), type), filename));
45
}
45
}
- a/Source/WebCore/editing/WebCorePasteboardFileReader.h -1 / +1 lines
Lines 41-47 struct WebCorePasteboardFileReader final : PasteboardFileReader { a/Source/WebCore/editing/WebCorePasteboardFileReader.h_sec1
41
    ~WebCorePasteboardFileReader();
41
    ~WebCorePasteboardFileReader();
42
42
43
    void readFilename(const String&) final;
43
    void readFilename(const String&) final;
44
    void readBuffer(const String& filename, const String& type, Ref<SharedBuffer>&&) final;
44
    void readBuffer(const String& filename, const String& type, Ref<FragmentedSharedBuffer>&&) final;
45
45
46
    RefPtr<ScriptExecutionContext> context;
46
    RefPtr<ScriptExecutionContext> context;
47
    Vector<Ref<File>> files;
47
    Vector<Ref<File>> files;
- a/Source/WebCore/editing/cocoa/HTMLConverter.mm -4 / +4 lines
Lines 1273-1279 BOOL HTMLConverter::_addAttachmentForElement(Element& element, NSURL *url, BOOL a/Source/WebCore/editing/cocoa/HTMLConverter.mm_sec1
1273
        if (auto resource = dataSource->subresource(url)) {
1273
        if (auto resource = dataSource->subresource(url)) {
1274
            auto& mimeType = resource->mimeType();
1274
            auto& mimeType = resource->mimeType();
1275
            if (!usePlaceholder || mimeType != "text/html") {
1275
            if (!usePlaceholder || mimeType != "text/html") {
1276
                fileWrapper = adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:resource->data().createNSData().get()]);
1276
                fileWrapper = adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:resource->data().makeContiguous()->createNSData().get()]);
1277
                [fileWrapper setPreferredFilename:suggestedFilenameWithMIMEType(url, mimeType)];
1277
                [fileWrapper setPreferredFilename:suggestedFilenameWithMIMEType(url, mimeType)];
1278
            } else
1278
            } else
1279
                notFound = YES;
1279
                notFound = YES;
Lines 2300-2306 static RetainPtr<NSFileWrapper> fileWrapperForURL(DocumentLoader* dataSource, NS a/Source/WebCore/editing/cocoa/HTMLConverter.mm_sec2
2300
2300
2301
    if (dataSource) {
2301
    if (dataSource) {
2302
        if (RefPtr<ArchiveResource> resource = dataSource->subresource(URL)) {
2302
        if (RefPtr<ArchiveResource> resource = dataSource->subresource(URL)) {
2303
            auto wrapper = adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:resource->data().createNSData().get()]);
2303
            auto wrapper = adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:resource->data().makeContiguous()->createNSData().get()]);
2304
            NSString *filename = resource->response().suggestedFilename();
2304
            NSString *filename = resource->response().suggestedFilename();
2305
            if (!filename || ![filename length])
2305
            if (!filename || ![filename length])
2306
                filename = suggestedFilenameWithMIMEType(resource->url(), resource->mimeType());
2306
                filename = suggestedFilenameWithMIMEType(resource->url(), resource->mimeType());
Lines 2322-2329 static RetainPtr<NSFileWrapper> fileWrapperForURL(DocumentLoader* dataSource, NS a/Source/WebCore/editing/cocoa/HTMLConverter.mm_sec3
2322
static RetainPtr<NSFileWrapper> fileWrapperForElement(HTMLImageElement& element)
2322
static RetainPtr<NSFileWrapper> fileWrapperForElement(HTMLImageElement& element)
2323
{
2323
{
2324
    if (CachedImage* cachedImage = element.cachedImage()) {
2324
    if (CachedImage* cachedImage = element.cachedImage()) {
2325
        if (SharedBuffer* sharedBuffer = cachedImage->resourceBuffer())
2325
        if (FragmentedSharedBuffer* sharedBuffer = cachedImage->resourceBuffer())
2326
            return adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:sharedBuffer->createNSData().get()]);
2326
            return adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:sharedBuffer->makeContiguous()->createNSData().get()]);
2327
    }
2327
    }
2328
2328
2329
    auto* renderer = element.renderer();
2329
    auto* renderer = element.renderer();
- a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm -20 / +20 lines
Lines 245-251 static bool supportsClientSideAttachmentData(const Frame& frame) a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec1
245
245
246
#endif
246
#endif
247
247
248
static Ref<DocumentFragment> createFragmentForImageAttachment(Frame& frame, Document& document, Ref<SharedBuffer>&& buffer, const String& contentType, PresentationSize preferredSize)
248
static Ref<DocumentFragment> createFragmentForImageAttachment(Frame& frame, Document& document, Ref<FragmentedSharedBuffer>&& buffer, const String& contentType, PresentationSize preferredSize)
249
{
249
{
250
#if ENABLE(ATTACHMENT_ELEMENT)
250
#if ENABLE(ATTACHMENT_ELEMENT)
251
    auto attachment = HTMLAttachmentElement::create(HTMLNames::attachmentTag, document);
251
    auto attachment = HTMLAttachmentElement::create(HTMLNames::attachmentTag, document);
Lines 309-315 static void replaceRichContentWithAttachments(Frame& frame, DocumentFragment& fr a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec2
309
            continue;
309
            continue;
310
310
311
        auto& resource = resourceEntry->value;
311
        auto& resource = resourceEntry->value;
312
        serializedAttachmentData.append({ attachment.uniqueIdentifier(), resource->mimeType(), resource->data() });
312
        serializedAttachmentData.append({ attachment.uniqueIdentifier(), resource->mimeType(), resource->data().makeContiguous() });
313
    }
313
    }
314
314
315
    if (!serializedAttachmentData.isEmpty())
315
    if (!serializedAttachmentData.isEmpty())
Lines 332-338 static void replaceRichContentWithAttachments(Frame& frame, DocumentFragment& fr a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec3
332
        if (name.isEmpty())
332
        if (name.isEmpty())
333
            name = "media"_s;
333
            name = "media"_s;
334
334
335
        attachmentInsertionInfo.append({ WTFMove(name), resource->value->mimeType(), resource->value->data(), image });
335
        attachmentInsertionInfo.append({ WTFMove(name), resource->value->mimeType(), resource->value->data().makeContiguous(), image });
336
    }
336
    }
337
337
338
    for (auto& object : descendantsOfType<HTMLObjectElement>(fragment)) {
338
    for (auto& object : descendantsOfType<HTMLObjectElement>(fragment)) {
Lines 350-356 static void replaceRichContentWithAttachments(Frame& frame, DocumentFragment& fr a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec4
350
        if (name.isEmpty())
350
        if (name.isEmpty())
351
            name = "file"_s;
351
            name = "file"_s;
352
352
353
        attachmentInsertionInfo.append({ WTFMove(name), resource->value->mimeType(), resource->value->data(), object });
353
        attachmentInsertionInfo.append({ WTFMove(name), resource->value->mimeType(), resource->value->data().makeContiguous(), object });
354
    }
354
    }
355
355
356
    for (auto& info : attachmentInsertionInfo) {
356
    for (auto& info : attachmentInsertionInfo) {
Lines 428-434 struct MarkupAndArchive { a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec5
428
    Ref<Archive> archive;
428
    Ref<Archive> archive;
429
};
429
};
430
430
431
static std::optional<MarkupAndArchive> extractMarkupAndArchive(SharedBuffer& buffer, const std::function<bool(const String)>& canShowMIMETypeAsHTML)
431
static std::optional<MarkupAndArchive> extractMarkupAndArchive(FragmentedSharedBuffer& buffer, const std::function<bool(const String)>& canShowMIMETypeAsHTML)
432
{
432
{
433
    auto archive = LegacyWebArchive::create(URL(), buffer);
433
    auto archive = LegacyWebArchive::create(URL(), buffer);
434
    if (!archive)
434
    if (!archive)
Lines 442-448 static std::optional<MarkupAndArchive> extractMarkupAndArchive(SharedBuffer& buf a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec6
442
    if (!canShowMIMETypeAsHTML(type))
442
    if (!canShowMIMETypeAsHTML(type))
443
        return std::nullopt;
443
        return std::nullopt;
444
444
445
    return MarkupAndArchive { String::fromUTF8(mainResource->data().data(), mainResource->data().size()), mainResource.releaseNonNull(), archive.releaseNonNull() };
445
    return MarkupAndArchive { String::fromUTF8(mainResource->data().makeContiguous()->data(), mainResource->data().size()), mainResource.releaseNonNull(), archive.releaseNonNull() };
446
}
446
}
447
447
448
static String sanitizeMarkupWithArchive(Frame& frame, Document& destinationDocument, MarkupAndArchive& markupAndArchive, MSOListQuirks msoListQuirks, const std::function<bool(const String)>& canShowMIMETypeAsHTML)
448
static String sanitizeMarkupWithArchive(Frame& frame, Document& destinationDocument, MarkupAndArchive& markupAndArchive, MSOListQuirks msoListQuirks, const std::function<bool(const String)>& canShowMIMETypeAsHTML)
Lines 481-487 static String sanitizeMarkupWithArchive(Frame& frame, Document& destinationDocum a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec7
481
        if (!shouldReplaceSubresourceURL(subframeURL))
481
        if (!shouldReplaceSubresourceURL(subframeURL))
482
            continue;
482
            continue;
483
483
484
        MarkupAndArchive subframeContent = { String::fromUTF8(subframeMainResource->data().data(), subframeMainResource->data().size()),
484
        MarkupAndArchive subframeContent = { String::fromUTF8(subframeMainResource->data().makeContiguous()->data(), subframeMainResource->data().size()),
485
            subframeMainResource.releaseNonNull(), subframeArchive.copyRef() };
485
            subframeMainResource.releaseNonNull(), subframeArchive.copyRef() };
486
        auto subframeMarkup = sanitizeMarkupWithArchive(frame, destinationDocument, subframeContent, MSOListQuirks::Disabled, canShowMIMETypeAsHTML);
486
        auto subframeMarkup = sanitizeMarkupWithArchive(frame, destinationDocument, subframeContent, MSOListQuirks::Disabled, canShowMIMETypeAsHTML);
487
487
Lines 497-503 static String sanitizeMarkupWithArchive(Frame& frame, Document& destinationDocum a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec8
497
    return sanitizedMarkupForFragmentInDocument(WTFMove(fragment), *stagingDocument, msoListQuirks, markupAndArchive.markup);
497
    return sanitizedMarkupForFragmentInDocument(WTFMove(fragment), *stagingDocument, msoListQuirks, markupAndArchive.markup);
498
}
498
}
499
499
500
bool WebContentReader::readWebArchive(SharedBuffer& buffer)
500
bool WebContentReader::readWebArchive(FragmentedSharedBuffer& buffer)
501
{
501
{
502
    if (frame.settings().preferMIMETypeForImages() || !frame.document())
502
    if (frame.settings().preferMIMETypeForImages() || !frame.document())
503
        return false;
503
        return false;
Lines 532-538 bool WebContentReader::readWebArchive(SharedBuffer& buffer) a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec9
532
    return true;
532
    return true;
533
}
533
}
534
534
535
bool WebContentMarkupReader::readWebArchive(SharedBuffer& buffer)
535
bool WebContentMarkupReader::readWebArchive(FragmentedSharedBuffer& buffer)
536
{
536
{
537
    if (!frame.document())
537
    if (!frame.document())
538
        return false;
538
        return false;
Lines 612-623 bool WebContentMarkupReader::readHTML(const String& string) a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec10
612
    return !markup.isEmpty();
612
    return !markup.isEmpty();
613
}
613
}
614
614
615
bool WebContentReader::readRTFD(SharedBuffer& buffer)
615
bool WebContentReader::readRTFD(FragmentedSharedBuffer& buffer)
616
{
616
{
617
    if (frame.settings().preferMIMETypeForImages() || !frame.document())
617
    if (frame.settings().preferMIMETypeForImages() || !frame.document())
618
        return false;
618
        return false;
619
619
620
    auto string = adoptNS([[NSAttributedString alloc] initWithRTFD:buffer.createNSData().get() documentAttributes:nullptr]);
620
    auto string = adoptNS([[NSAttributedString alloc] initWithRTFD:buffer.makeContiguous()->createNSData().get() documentAttributes:nullptr]);
621
    auto fragment = createFragmentAndAddResources(frame, string.get());
621
    auto fragment = createFragmentAndAddResources(frame, string.get());
622
    if (!fragment)
622
    if (!fragment)
623
        return false;
623
        return false;
Lines 626-636 bool WebContentReader::readRTFD(SharedBuffer& buffer) a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec11
626
    return true;
626
    return true;
627
}
627
}
628
628
629
bool WebContentMarkupReader::readRTFD(SharedBuffer& buffer)
629
bool WebContentMarkupReader::readRTFD(FragmentedSharedBuffer& buffer)
630
{
630
{
631
    if (!frame.document())
631
    if (!frame.document())
632
        return false;
632
        return false;
633
    auto string = adoptNS([[NSAttributedString alloc] initWithRTFD:buffer.createNSData().get() documentAttributes:nullptr]);
633
    auto string = adoptNS([[NSAttributedString alloc] initWithRTFD:buffer.makeContiguous()->createNSData().get() documentAttributes:nullptr]);
634
    auto fragment = createFragmentAndAddResources(frame, string.get());
634
    auto fragment = createFragmentAndAddResources(frame, string.get());
635
    if (!fragment)
635
    if (!fragment)
636
        return false;
636
        return false;
Lines 639-650 bool WebContentMarkupReader::readRTFD(SharedBuffer& buffer) a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec12
639
    return true;
639
    return true;
640
}
640
}
641
641
642
bool WebContentReader::readRTF(SharedBuffer& buffer)
642
bool WebContentReader::readRTF(FragmentedSharedBuffer& buffer)
643
{
643
{
644
    if (frame.settings().preferMIMETypeForImages())
644
    if (frame.settings().preferMIMETypeForImages())
645
        return false;
645
        return false;
646
646
647
    auto string = adoptNS([[NSAttributedString alloc] initWithRTF:buffer.createNSData().get() documentAttributes:nullptr]);
647
    auto string = adoptNS([[NSAttributedString alloc] initWithRTF:buffer.makeContiguous()->createNSData().get() documentAttributes:nullptr]);
648
    auto fragment = createFragmentAndAddResources(frame, string.get());
648
    auto fragment = createFragmentAndAddResources(frame, string.get());
649
    if (!fragment)
649
    if (!fragment)
650
        return false;
650
        return false;
Lines 653-663 bool WebContentReader::readRTF(SharedBuffer& buffer) a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec13
653
    return true;
653
    return true;
654
}
654
}
655
655
656
bool WebContentMarkupReader::readRTF(SharedBuffer& buffer)
656
bool WebContentMarkupReader::readRTF(FragmentedSharedBuffer& buffer)
657
{
657
{
658
    if (!frame.document())
658
    if (!frame.document())
659
        return false;
659
        return false;
660
    auto string = adoptNS([[NSAttributedString alloc] initWithRTF:buffer.createNSData().get() documentAttributes:nullptr]);
660
    auto string = adoptNS([[NSAttributedString alloc] initWithRTF:buffer.makeContiguous()->createNSData().get() documentAttributes:nullptr]);
661
    auto fragment = createFragmentAndAddResources(frame, string.get());
661
    auto fragment = createFragmentAndAddResources(frame, string.get());
662
    if (!fragment)
662
    if (!fragment)
663
        return false;
663
        return false;
Lines 676-682 bool WebContentReader::readPlainText(const String& text) a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec14
676
    return true;
676
    return true;
677
}
677
}
678
678
679
bool WebContentReader::readImage(Ref<SharedBuffer>&& buffer, const String& type, PresentationSize preferredPresentationSize)
679
bool WebContentReader::readImage(Ref<FragmentedSharedBuffer>&& buffer, const String& type, PresentationSize preferredPresentationSize)
680
{
680
{
681
    ASSERT(frame.document());
681
    ASSERT(frame.document());
682
    auto& document = *frame.document();
682
    auto& document = *frame.document();
Lines 746-752 ALLOW_DEPRECATED_DECLARATIONS_END a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec15
746
    return attachment;
746
    return attachment;
747
}
747
}
748
748
749
static Ref<HTMLElement> attachmentForData(Frame& frame, SharedBuffer& buffer, const String& contentType, const String& name, PresentationSize preferredSize)
749
static Ref<HTMLElement> attachmentForData(Frame& frame, FragmentedSharedBuffer& buffer, const String& contentType, const String& name, PresentationSize preferredSize)
750
{
750
{
751
    Ref document = *frame.document();
751
    Ref document = *frame.document();
752
    auto attachment = HTMLAttachmentElement::create(HTMLNames::attachmentTag, document);
752
    auto attachment = HTMLAttachmentElement::create(HTMLNames::attachmentTag, document);
Lines 833-839 bool WebContentReader::readURL(const URL& url, const String& title) a/Source/WebCore/editing/cocoa/WebContentReaderCocoa.mm_sec16
833
    return true;
833
    return true;
834
}
834
}
835
835
836
bool WebContentReader::readDataBuffer(SharedBuffer& buffer, const String& type, const String& name, PresentationSize preferredPresentationSize)
836
bool WebContentReader::readDataBuffer(FragmentedSharedBuffer& buffer, const String& type, const String& name, PresentationSize preferredPresentationSize)
837
{
837
{
838
    if (buffer.isEmpty())
838
    if (buffer.isEmpty())
839
        return false;
839
        return false;
- a/Source/WebCore/editing/gtk/WebContentReaderGtk.cpp -1 / +1 lines
Lines 71-77 bool WebContentReader::readPlainText(const String& text) a/Source/WebCore/editing/gtk/WebContentReaderGtk.cpp_sec1
71
    return true;
71
    return true;
72
}
72
}
73
73
74
bool WebContentReader::readImage(Ref<SharedBuffer>&& buffer, const String& type, PresentationSize preferredPresentationSize)
74
bool WebContentReader::readImage(Ref<FragmentedSharedBuffer>&& buffer, const String& type, PresentationSize preferredPresentationSize)
75
{
75
{
76
    ASSERT(frame.document());
76
    ASSERT(frame.document());
77
    auto& document = *frame.document();
77
    auto& document = *frame.document();
- a/Source/WebCore/fileapi/Blob.h -1 / +1 lines
Lines 53-59 class BlobLoader; a/Source/WebCore/fileapi/Blob.h_sec1
53
class DeferredPromise;
53
class DeferredPromise;
54
class ReadableStream;
54
class ReadableStream;
55
class ScriptExecutionContext;
55
class ScriptExecutionContext;
56
class SharedBuffer;
56
class FragmentedSharedBuffer;
57
57
58
template<typename> class ExceptionOr;
58
template<typename> class ExceptionOr;
59
59
- a/Source/WebCore/fileapi/NetworkSendQueue.cpp -1 / +1 lines
Lines 94-100 void NetworkSendQueue::processMessages() a/Source/WebCore/fileapi/NetworkSendQueue.cpp_sec1
94
        bool shouldStopProcessing = false;
94
        bool shouldStopProcessing = false;
95
        switchOn(m_queue.first(), [this](const CString& utf8) {
95
        switchOn(m_queue.first(), [this](const CString& utf8) {
96
            m_writeString(utf8);
96
            m_writeString(utf8);
97
        }, [this](Ref<SharedBuffer>& data) {
97
        }, [this](Ref<FragmentedSharedBuffer>& data) {
98
            data->forEachSegment(m_writeRawData);
98
            data->forEachSegment(m_writeRawData);
99
        }, [this, &shouldStopProcessing](UniqueRef<BlobLoader>& loader) {
99
        }, [this, &shouldStopProcessing](UniqueRef<BlobLoader>& loader) {
100
            auto errorCode = loader->errorCode();
100
            auto errorCode = loader->errorCode();
- a/Source/WebCore/fileapi/NetworkSendQueue.h -2 / +2 lines
Lines 43-49 namespace WebCore { a/Source/WebCore/fileapi/NetworkSendQueue.h_sec1
43
43
44
class Blob;
44
class Blob;
45
class BlobLoader;
45
class BlobLoader;
46
class SharedBuffer;
46
class FragmentedSharedBuffer;
47
47
48
class WEBCORE_EXPORT NetworkSendQueue : public ContextDestructionObserver {
48
class WEBCORE_EXPORT NetworkSendQueue : public ContextDestructionObserver {
49
public:
49
public:
Lines 63-69 public: a/Source/WebCore/fileapi/NetworkSendQueue.h_sec2
63
private:
63
private:
64
    void processMessages();
64
    void processMessages();
65
65
66
    using Message = std::variant<CString, Ref<SharedBuffer>, UniqueRef<BlobLoader>>;
66
    using Message = std::variant<CString, Ref<FragmentedSharedBuffer>, UniqueRef<BlobLoader>>;
67
    Deque<Message> m_queue;
67
    Deque<Message> m_queue;
68
68
69
    WriteString m_writeString;
69
    WriteString m_writeString;
- a/Source/WebCore/html/HTMLAttachmentElement.cpp -1 / +1 lines
Lines 227-233 static bool mimeTypeIsSuitableForInlineImageAttachment(const String& mimeType) a/Source/WebCore/html/HTMLAttachmentElement.cpp_sec1
227
    return MIMETypeRegistry::isSupportedImageMIMEType(mimeType) || MIMETypeRegistry::isPDFMIMEType(mimeType);
227
    return MIMETypeRegistry::isSupportedImageMIMEType(mimeType) || MIMETypeRegistry::isPDFMIMEType(mimeType);
228
}
228
}
229
229
230
void HTMLAttachmentElement::updateEnclosingImageWithData(const String& contentType, Ref<SharedBuffer>&& buffer)
230
void HTMLAttachmentElement::updateEnclosingImageWithData(const String& contentType, Ref<FragmentedSharedBuffer>&& buffer)
231
{
231
{
232
    auto* hostElement = shadowHost();
232
    auto* hostElement = shadowHost();
233
    if (!is<HTMLImageElement>(hostElement) || !buffer->size())
233
    if (!is<HTMLImageElement>(hostElement) || !buffer->size())
- a/Source/WebCore/html/HTMLAttachmentElement.h -2 / +2 lines
Lines 36-42 class File; a/Source/WebCore/html/HTMLAttachmentElement.h_sec1
36
class HTMLImageElement;
36
class HTMLImageElement;
37
class RenderAttachment;
37
class RenderAttachment;
38
class ShareableBitmap;
38
class ShareableBitmap;
39
class SharedBuffer;
39
class FragmentedSharedBuffer;
40
40
41
class HTMLAttachmentElement final : public HTMLElement {
41
class HTMLAttachmentElement final : public HTMLElement {
42
    WTF_MAKE_ISO_ALLOCATED(HTMLAttachmentElement);
42
    WTF_MAKE_ISO_ALLOCATED(HTMLAttachmentElement);
Lines 57-63 public: a/Source/WebCore/html/HTMLAttachmentElement.h_sec2
57
    void copyNonAttributePropertiesFromElement(const Element&) final;
57
    void copyNonAttributePropertiesFromElement(const Element&) final;
58
58
59
    WEBCORE_EXPORT void updateAttributes(std::optional<uint64_t>&& newFileSize, const String& newContentType, const String& newFilename);
59
    WEBCORE_EXPORT void updateAttributes(std::optional<uint64_t>&& newFileSize, const String& newContentType, const String& newFilename);
60
    WEBCORE_EXPORT void updateEnclosingImageWithData(const String& contentType, Ref<SharedBuffer>&& data);
60
    WEBCORE_EXPORT void updateEnclosingImageWithData(const String& contentType, Ref<FragmentedSharedBuffer>&& data);
61
    WEBCORE_EXPORT void updateThumbnail(const RefPtr<Image>& thumbnail);
61
    WEBCORE_EXPORT void updateThumbnail(const RefPtr<Image>& thumbnail);
62
62
63
    InsertedIntoAncestorResult insertedIntoAncestor(InsertionType, ContainerNode&) final;
63
    InsertedIntoAncestorResult insertedIntoAncestor(InsertionType, ContainerNode&) final;
- a/Source/WebCore/html/HTMLMediaElement.cpp -1 / +1 lines
Lines 2938-2944 void HTMLMediaElement::cdmClientAttemptToResumePlaybackIfNecessary() a/Source/WebCore/html/HTMLMediaElement.cpp_sec1
2938
    attemptToResumePlaybackIfNecessary();
2938
    attemptToResumePlaybackIfNecessary();
2939
}
2939
}
2940
2940
2941
void HTMLMediaElement::cdmClientUnrequestedInitializationDataReceived(const String& initDataType, Ref<SharedBuffer>&& initData)
2941
void HTMLMediaElement::cdmClientUnrequestedInitializationDataReceived(const String& initDataType, Ref<FragmentedSharedBuffer>&& initData)
2942
{
2942
{
2943
    mediaPlayerInitializationDataEncountered(initDataType, initData->tryCreateArrayBuffer());
2943
    mediaPlayerInitializationDataEncountered(initDataType, initData->tryCreateArrayBuffer());
2944
}
2944
}
- a/Source/WebCore/html/HTMLMediaElement.h -1 / +1 lines
Lines 720-726 private: a/Source/WebCore/html/HTMLMediaElement.h_sec1
720
720
721
    // CDMClient
721
    // CDMClient
722
    void cdmClientAttemptToResumePlaybackIfNecessary() final;
722
    void cdmClientAttemptToResumePlaybackIfNecessary() final;
723
    void cdmClientUnrequestedInitializationDataReceived(const String&, Ref<SharedBuffer>&&) final;
723
    void cdmClientUnrequestedInitializationDataReceived(const String&, Ref<FragmentedSharedBuffer>&&) final;
724
#endif
724
#endif
725
725
726
#if ENABLE(LEGACY_ENCRYPTED_MEDIA) && ENABLE(ENCRYPTED_MEDIA)
726
#if ENABLE(LEGACY_ENCRYPTED_MEDIA) && ENABLE(ENCRYPTED_MEDIA)
- a/Source/WebCore/html/ImageDocument.cpp -2 / +2 lines
Lines 141-147 void ImageDocument::updateDuringParsing() a/Source/WebCore/html/ImageDocument.cpp_sec1
141
    if (!m_imageElement)
141
    if (!m_imageElement)
142
        createDocumentStructure();
142
        createDocumentStructure();
143
143
144
    if (RefPtr<SharedBuffer> buffer = loader()->mainResourceData())
144
    if (RefPtr<FragmentedSharedBuffer> buffer = loader()->mainResourceData())
145
        m_imageElement->cachedImage()->updateBuffer(*buffer);
145
        m_imageElement->cachedImage()->updateBuffer(*buffer);
146
146
147
    imageUpdated();
147
    imageUpdated();
Lines 151-157 void ImageDocument::finishedParsing() a/Source/WebCore/html/ImageDocument.cpp_sec2
151
{
151
{
152
    if (!parser()->isStopped() && m_imageElement) {
152
    if (!parser()->isStopped() && m_imageElement) {
153
        CachedImage& cachedImage = *m_imageElement->cachedImage();
153
        CachedImage& cachedImage = *m_imageElement->cachedImage();
154
        RefPtr<SharedBuffer> data = loader()->mainResourceData();
154
        RefPtr<FragmentedSharedBuffer> data = loader()->mainResourceData();
155
155
156
        // If this is a multipart image, make a copy of the current part, since the resource data
156
        // If this is a multipart image, make a copy of the current part, since the resource data
157
        // will be overwritten by the next part.
157
        // will be overwritten by the next part.
- a/Source/WebCore/inspector/InspectorInstrumentation.cpp -1 / +1 lines
Lines 850-856 void InspectorInstrumentation::interceptRequestImpl(InstrumentingAgents& instrum a/Source/WebCore/inspector/InspectorInstrumentation.cpp_sec1
850
        networkAgent->interceptRequest(loader, WTFMove(handler));
850
        networkAgent->interceptRequest(loader, WTFMove(handler));
851
}
851
}
852
852
853
void InspectorInstrumentation::interceptResponseImpl(InstrumentingAgents& instrumentingAgents, const ResourceResponse& response, ResourceLoaderIdentifier identifier, CompletionHandler<void(const ResourceResponse&, RefPtr<SharedBuffer>)>&& handler)
853
void InspectorInstrumentation::interceptResponseImpl(InstrumentingAgents& instrumentingAgents, const ResourceResponse& response, ResourceLoaderIdentifier identifier, CompletionHandler<void(const ResourceResponse&, RefPtr<FragmentedSharedBuffer>)>&& handler)
854
{
854
{
855
    if (auto* networkAgent = instrumentingAgents.enabledNetworkAgent())
855
    if (auto* networkAgent = instrumentingAgents.enabledNetworkAgent())
856
        networkAgent->interceptResponse(response, identifier, WTFMove(handler));
856
        networkAgent->interceptResponse(response, identifier, WTFMove(handler));
- a/Source/WebCore/inspector/InspectorInstrumentation.h -4 / +4 lines
Lines 93-99 class ResourceResponse; a/Source/WebCore/inspector/InspectorInstrumentation.h_sec1
93
class ScriptExecutionContext;
93
class ScriptExecutionContext;
94
class SecurityOrigin;
94
class SecurityOrigin;
95
class ShadowRoot;
95
class ShadowRoot;
96
class SharedBuffer;
96
class FragmentedSharedBuffer;
97
class TimerBase;
97
class TimerBase;
98
class WebKitNamedFlow;
98
class WebKitNamedFlow;
99
class WebSocketChannel;
99
class WebSocketChannel;
Lines 236-242 public: a/Source/WebCore/inspector/InspectorInstrumentation.h_sec2
236
    static bool shouldInterceptRequest(const Frame&, const ResourceRequest&);
236
    static bool shouldInterceptRequest(const Frame&, const ResourceRequest&);
237
    static bool shouldInterceptResponse(const Frame&, const ResourceResponse&);
237
    static bool shouldInterceptResponse(const Frame&, const ResourceResponse&);
238
    static void interceptRequest(ResourceLoader&, Function<void(const ResourceRequest&)>&&);
238
    static void interceptRequest(ResourceLoader&, Function<void(const ResourceRequest&)>&&);
239
    static void interceptResponse(const Frame&, const ResourceResponse&, ResourceLoaderIdentifier, CompletionHandler<void(const ResourceResponse&, RefPtr<SharedBuffer>)>&&);
239
    static void interceptResponse(const Frame&, const ResourceResponse&, ResourceLoaderIdentifier, CompletionHandler<void(const ResourceResponse&, RefPtr<FragmentedSharedBuffer>)>&&);
240
240
241
    static void addMessageToConsole(Page&, std::unique_ptr<Inspector::ConsoleMessage>);
241
    static void addMessageToConsole(Page&, std::unique_ptr<Inspector::ConsoleMessage>);
242
    static void addMessageToConsole(WorkerOrWorkletGlobalScope&, std::unique_ptr<Inspector::ConsoleMessage>);
242
    static void addMessageToConsole(WorkerOrWorkletGlobalScope&, std::unique_ptr<Inspector::ConsoleMessage>);
Lines 441-447 private: a/Source/WebCore/inspector/InspectorInstrumentation.h_sec3
441
    static bool shouldInterceptRequestImpl(InstrumentingAgents&, const ResourceRequest&);
441
    static bool shouldInterceptRequestImpl(InstrumentingAgents&, const ResourceRequest&);
442
    static bool shouldInterceptResponseImpl(InstrumentingAgents&, const ResourceResponse&);
442
    static bool shouldInterceptResponseImpl(InstrumentingAgents&, const ResourceResponse&);
443
    static void interceptRequestImpl(InstrumentingAgents&, ResourceLoader&, Function<void(const ResourceRequest&)>&&);
443
    static void interceptRequestImpl(InstrumentingAgents&, ResourceLoader&, Function<void(const ResourceRequest&)>&&);
444
    static void interceptResponseImpl(InstrumentingAgents&, const ResourceResponse&, ResourceLoaderIdentifier, CompletionHandler<void(const ResourceResponse&, RefPtr<SharedBuffer>)>&&);
444
    static void interceptResponseImpl(InstrumentingAgents&, const ResourceResponse&, ResourceLoaderIdentifier, CompletionHandler<void(const ResourceResponse&, RefPtr<FragmentedSharedBuffer>)>&&);
445
445
446
    static void addMessageToConsoleImpl(InstrumentingAgents&, std::unique_ptr<Inspector::ConsoleMessage>);
446
    static void addMessageToConsoleImpl(InstrumentingAgents&, std::unique_ptr<Inspector::ConsoleMessage>);
447
447
Lines 1289-1295 inline void InspectorInstrumentation::interceptRequest(ResourceLoader& loader, F a/Source/WebCore/inspector/InspectorInstrumentation.h_sec4
1289
        interceptRequestImpl(*agents, loader, WTFMove(handler));
1289
        interceptRequestImpl(*agents, loader, WTFMove(handler));
1290
}
1290
}
1291
1291
1292
inline void InspectorInstrumentation::interceptResponse(const Frame& frame, const ResourceResponse& response, ResourceLoaderIdentifier identifier, CompletionHandler<void(const ResourceResponse&, RefPtr<SharedBuffer>)>&& handler)
1292
inline void InspectorInstrumentation::interceptResponse(const Frame& frame, const ResourceResponse& response, ResourceLoaderIdentifier identifier, CompletionHandler<void(const ResourceResponse&, RefPtr<FragmentedSharedBuffer>)>&& handler)
1293
{
1293
{
1294
    ASSERT(InspectorInstrumentation::shouldInterceptResponse(frame, response));
1294
    ASSERT(InspectorInstrumentation::shouldInterceptResponse(frame, response));
1295
    if (auto* agents = instrumentingAgents(frame))
1295
    if (auto* agents = instrumentingAgents(frame))
- a/Source/WebCore/inspector/InspectorInstrumentationWebKit.cpp -1 / +1 lines
Lines 45-51 void InspectorInstrumentationWebKit::interceptRequestInternal(ResourceLoader& lo a/Source/WebCore/inspector/InspectorInstrumentationWebKit.cpp_sec1
45
    InspectorInstrumentation::interceptRequest(loader, WTFMove(handler));
45
    InspectorInstrumentation::interceptRequest(loader, WTFMove(handler));
46
}
46
}
47
47
48
void InspectorInstrumentationWebKit::interceptResponseInternal(const Frame& frame, const ResourceResponse& response, ResourceLoaderIdentifier identifier, CompletionHandler<void(const ResourceResponse&, RefPtr<SharedBuffer>)>&& handler)
48
void InspectorInstrumentationWebKit::interceptResponseInternal(const Frame& frame, const ResourceResponse& response, ResourceLoaderIdentifier identifier, CompletionHandler<void(const ResourceResponse&, RefPtr<FragmentedSharedBuffer>)>&& handler)
49
{
49
{
50
    InspectorInstrumentation::interceptResponse(frame, response, identifier, WTFMove(handler));
50
    InspectorInstrumentation::interceptResponse(frame, response, identifier, WTFMove(handler));
51
}
51
}
- a/Source/WebCore/inspector/InspectorInstrumentationWebKit.h -4 / +4 lines
Lines 36-55 class Frame; a/Source/WebCore/inspector/InspectorInstrumentationWebKit.h_sec1
36
class ResourceLoader;
36
class ResourceLoader;
37
class ResourceRequest;
37
class ResourceRequest;
38
class ResourceResponse;
38
class ResourceResponse;
39
class SharedBuffer;
39
class FragmentedSharedBuffer;
40
40
41
class WEBCORE_EXPORT InspectorInstrumentationWebKit {
41
class WEBCORE_EXPORT InspectorInstrumentationWebKit {
42
public:
42
public:
43
    static bool shouldInterceptRequest(const Frame*, const ResourceRequest&);
43
    static bool shouldInterceptRequest(const Frame*, const ResourceRequest&);
44
    static bool shouldInterceptResponse(const Frame*, const ResourceResponse&);
44
    static bool shouldInterceptResponse(const Frame*, const ResourceResponse&);
45
    static void interceptRequest(ResourceLoader&, Function<void(const ResourceRequest&)>&&);
45
    static void interceptRequest(ResourceLoader&, Function<void(const ResourceRequest&)>&&);
46
    static void interceptResponse(const Frame*, const ResourceResponse&, ResourceLoaderIdentifier, CompletionHandler<void(const ResourceResponse&, RefPtr<SharedBuffer>)>&&);
46
    static void interceptResponse(const Frame*, const ResourceResponse&, ResourceLoaderIdentifier, CompletionHandler<void(const ResourceResponse&, RefPtr<FragmentedSharedBuffer>)>&&);
47
47
48
private:
48
private:
49
    static bool shouldInterceptRequestInternal(const Frame&, const ResourceRequest&);
49
    static bool shouldInterceptRequestInternal(const Frame&, const ResourceRequest&);
50
    static bool shouldInterceptResponseInternal(const Frame&, const ResourceResponse&);
50
    static bool shouldInterceptResponseInternal(const Frame&, const ResourceResponse&);
51
    static void interceptRequestInternal(ResourceLoader&, Function<void(const ResourceRequest&)>&&);
51
    static void interceptRequestInternal(ResourceLoader&, Function<void(const ResourceRequest&)>&&);
52
    static void interceptResponseInternal(const Frame&, const ResourceResponse&, ResourceLoaderIdentifier, CompletionHandler<void(const ResourceResponse&, RefPtr<SharedBuffer>)>&&);
52
    static void interceptResponseInternal(const Frame&, const ResourceResponse&, ResourceLoaderIdentifier, CompletionHandler<void(const ResourceResponse&, RefPtr<FragmentedSharedBuffer>)>&&);
53
};
53
};
54
54
55
inline bool InspectorInstrumentationWebKit::shouldInterceptRequest(const Frame* frame, const ResourceRequest& request)
55
inline bool InspectorInstrumentationWebKit::shouldInterceptRequest(const Frame* frame, const ResourceRequest& request)
Lines 76-82 inline void InspectorInstrumentationWebKit::interceptRequest(ResourceLoader& loa a/Source/WebCore/inspector/InspectorInstrumentationWebKit.h_sec2
76
    interceptRequestInternal(loader, WTFMove(handler));
76
    interceptRequestInternal(loader, WTFMove(handler));
77
}
77
}
78
78
79
inline void InspectorInstrumentationWebKit::interceptResponse(const Frame* frame, const ResourceResponse& response, ResourceLoaderIdentifier identifier, CompletionHandler<void(const ResourceResponse&, RefPtr<SharedBuffer>)>&& handler)
79
inline void InspectorInstrumentationWebKit::interceptResponse(const Frame* frame, const ResourceResponse& response, ResourceLoaderIdentifier identifier, CompletionHandler<void(const ResourceResponse&, RefPtr<FragmentedSharedBuffer>)>&& handler)
80
{
80
{
81
    ASSERT(InspectorInstrumentationWebKit::shouldInterceptResponse(frame, response));
81
    ASSERT(InspectorInstrumentationWebKit::shouldInterceptResponse(frame, response));
82
    interceptResponseInternal(*frame, response, identifier, WTFMove(handler));
82
    interceptResponseInternal(*frame, response, identifier, WTFMove(handler));
- a/Source/WebCore/inspector/NetworkResourcesData.cpp -12 / +14 lines
Lines 47-52 static const size_t maximumSingleResourceContentSize = 50 * 1000 * 1000; // 50MB a/Source/WebCore/inspector/NetworkResourcesData.cpp_sec1
47
NetworkResourcesData::ResourceData::ResourceData(const String& requestId, const String& loaderId)
47
NetworkResourcesData::ResourceData::ResourceData(const String& requestId, const String& loaderId)
48
    : m_requestId(requestId)
48
    : m_requestId(requestId)
49
    , m_loaderId(loaderId)
49
    , m_loaderId(loaderId)
50
    , m_dataBuffer(makeUniqueRef<SharedBufferBuilder>())
50
{
51
{
51
}
52
}
52
53
Lines 64-70 unsigned NetworkResourcesData::ResourceData::removeContent() a/Source/WebCore/inspector/NetworkResourcesData.cpp_sec2
64
    if (hasData()) {
65
    if (hasData()) {
65
        ASSERT(!hasContent());
66
        ASSERT(!hasContent());
66
        result = m_dataBuffer->size();
67
        result = m_dataBuffer->size();
67
        m_dataBuffer = nullptr;
68
        m_dataBuffer->reset();
68
    }
69
    }
69
70
70
    if (hasContent()) {
71
    if (hasContent()) {
Lines 81-116 unsigned NetworkResourcesData::ResourceData::evictContent() a/Source/WebCore/inspector/NetworkResourcesData.cpp_sec3
81
    return removeContent();
82
    return removeContent();
82
}
83
}
83
84
85
bool NetworkResourcesData::ResourceData::hasData() const
86
{
87
    return !m_dataBuffer->isNull();
88
}
89
84
size_t NetworkResourcesData::ResourceData::dataLength() const
90
size_t NetworkResourcesData::ResourceData::dataLength() const
85
{
91
{
86
    return m_dataBuffer ? m_dataBuffer->size() : 0;
92
    return m_dataBuffer->size();
87
}
93
}
88
94
89
void NetworkResourcesData::ResourceData::appendData(const uint8_t* data, size_t dataLength)
95
void NetworkResourcesData::ResourceData::appendData(const uint8_t* data, size_t dataLength)
90
{
96
{
91
    ASSERT(!hasContent());
97
    ASSERT(!hasContent());
92
    if (!m_dataBuffer)
98
    m_dataBuffer->append(data, dataLength);
93
        m_dataBuffer = SharedBuffer::create(data, dataLength);
94
    else
95
        m_dataBuffer->append(data, dataLength);
96
}
99
}
97
100
98
unsigned NetworkResourcesData::ResourceData::decodeDataToContent()
101
unsigned NetworkResourcesData::ResourceData::decodeDataToContent()
99
{
102
{
100
    ASSERT(!hasContent());
103
    ASSERT(!hasContent());
101
104
102
    size_t dataLength = m_dataBuffer->size();
105
    auto buffer = m_dataBuffer->take()->makeContiguous();
106
    size_t dataLength = buffer->size();
103
107
104
    if (m_decoder) {
108
    if (m_decoder) {
105
        m_base64Encoded = false;
109
        m_base64Encoded = false;
106
        m_content = m_decoder->decodeAndFlush(m_dataBuffer->data(), dataLength);
110
        m_content = m_decoder->decodeAndFlush(buffer->data(), dataLength);
107
    } else {
111
    } else {
108
        m_base64Encoded = true;
112
        m_base64Encoded = true;
109
        m_content = base64EncodeToString(m_dataBuffer->data(), dataLength);
113
        m_content = base64EncodeToString(buffer->data(), dataLength);
110
    }
114
    }
111
115
112
    m_dataBuffer = nullptr;
113
114
    return m_content.sizeInBytes() - dataLength;
116
    return m_content.sizeInBytes() - dataLength;
115
}
117
}
116
118
Lines 267-273 void NetworkResourcesData::addCachedResource(const String& requestId, CachedReso a/Source/WebCore/inspector/NetworkResourcesData.cpp_sec4
267
    resourceData->setCachedResource(cachedResource);
269
    resourceData->setCachedResource(cachedResource);
268
}
270
}
269
271
270
void NetworkResourcesData::addResourceSharedBuffer(const String& requestId, RefPtr<SharedBuffer>&& buffer, const String& textEncodingName)
272
void NetworkResourcesData::addResourceSharedBuffer(const String& requestId, RefPtr<FragmentedSharedBuffer>&& buffer, const String& textEncodingName)
271
{
273
{
272
    ResourceData* resourceData = resourceDataForRequestId(requestId);
274
    ResourceData* resourceData = resourceDataForRequestId(requestId);
273
    if (!resourceData)
275
    if (!resourceData)
- a/Source/WebCore/inspector/NetworkResourcesData.h -8 / +10 lines
Lines 32-37 a/Source/WebCore/inspector/NetworkResourcesData.h_sec1
32
#include "InspectorPageAgent.h"
32
#include "InspectorPageAgent.h"
33
#include <wtf/Deque.h>
33
#include <wtf/Deque.h>
34
#include <wtf/HashMap.h>
34
#include <wtf/HashMap.h>
35
#include <wtf/UniqueRef.h>
35
#include <wtf/WallTime.h>
36
#include <wtf/WallTime.h>
36
#include <wtf/text/WTFString.h>
37
#include <wtf/text/WTFString.h>
37
38
Lines 40-46 namespace WebCore { a/Source/WebCore/inspector/NetworkResourcesData.h_sec2
40
class CachedResource;
41
class CachedResource;
41
class ResourceResponse;
42
class ResourceResponse;
42
class TextResourceDecoder;
43
class TextResourceDecoder;
43
class SharedBuffer;
44
class FragmentedSharedBuffer;
45
class SharedBufferBuilder;
44
46
45
class NetworkResourcesData {
47
class NetworkResourcesData {
46
    WTF_MAKE_FAST_ALLOCATED;
48
    WTF_MAKE_FAST_ALLOCATED;
Lines 88-95 public: a/Source/WebCore/inspector/NetworkResourcesData.h_sec3
88
        RefPtr<TextResourceDecoder> decoder() const { return m_decoder.copyRef(); }
90
        RefPtr<TextResourceDecoder> decoder() const { return m_decoder.copyRef(); }
89
        void setDecoder(RefPtr<TextResourceDecoder>&& decoder) { m_decoder = WTFMove(decoder); }
91
        void setDecoder(RefPtr<TextResourceDecoder>&& decoder) { m_decoder = WTFMove(decoder); }
90
92
91
        RefPtr<SharedBuffer> buffer() const { return m_buffer.copyRef(); }
93
        RefPtr<FragmentedSharedBuffer> buffer() const { return m_buffer.copyRef(); }
92
        void setBuffer(RefPtr<SharedBuffer>&& buffer) { m_buffer = WTFMove(buffer); }
94
        void setBuffer(RefPtr<FragmentedSharedBuffer>&& buffer) { m_buffer = WTFMove(buffer); }
93
95
94
        const std::optional<CertificateInfo>& certificateInfo() const { return m_certificateInfo; }
96
        const std::optional<CertificateInfo>& certificateInfo() const { return m_certificateInfo; }
95
        void setCertificateInfo(const std::optional<CertificateInfo>& certificateInfo) { m_certificateInfo = certificateInfo; }
97
        void setCertificateInfo(const std::optional<CertificateInfo>& certificateInfo) { m_certificateInfo = certificateInfo; }
Lines 103-112 public: a/Source/WebCore/inspector/NetworkResourcesData.h_sec4
103
        WallTime responseTimestamp() const { return m_responseTimestamp; }
105
        WallTime responseTimestamp() const { return m_responseTimestamp; }
104
        void setResponseTimestamp(WallTime time) { m_responseTimestamp = time; }
106
        void setResponseTimestamp(WallTime time) { m_responseTimestamp = time; }
105
107
106
        bool hasBufferedData() const { return m_dataBuffer; }
108
        bool hasBufferedData() const { return hasData(); }
107
109
108
    private:
110
    private:
109
        bool hasData() const { return m_dataBuffer; }
111
        bool hasData() const;
110
        size_t dataLength() const;
112
        size_t dataLength() const;
111
        void appendData(const uint8_t* data, size_t dataLength);
113
        void appendData(const uint8_t* data, size_t dataLength);
112
        unsigned decodeDataToContent();
114
        unsigned decodeDataToContent();
Lines 119-126 public: a/Source/WebCore/inspector/NetworkResourcesData.h_sec5
119
        String m_textEncodingName;
121
        String m_textEncodingName;
120
        String m_mimeType;
122
        String m_mimeType;
121
        RefPtr<TextResourceDecoder> m_decoder;
123
        RefPtr<TextResourceDecoder> m_decoder;
122
        RefPtr<SharedBuffer> m_dataBuffer;
124
        UniqueRef<SharedBufferBuilder> m_dataBuffer;
123
        RefPtr<SharedBuffer> m_buffer;
125
        RefPtr<FragmentedSharedBuffer> m_buffer;
124
        std::optional<CertificateInfo> m_certificateInfo;
126
        std::optional<CertificateInfo> m_certificateInfo;
125
        CachedResource* m_cachedResource { nullptr };
127
        CachedResource* m_cachedResource { nullptr };
126
        InspectorPageAgent::ResourceType m_type { InspectorPageAgent::OtherResource };
128
        InspectorPageAgent::ResourceType m_type { InspectorPageAgent::OtherResource };
Lines 144-150 public: a/Source/WebCore/inspector/NetworkResourcesData.h_sec6
144
    ResourceData const* maybeAddResourceData(const String& requestId, const uint8_t* data, size_t dataLength);
146
    ResourceData const* maybeAddResourceData(const String& requestId, const uint8_t* data, size_t dataLength);
145
    void maybeDecodeDataToContent(const String& requestId);
147
    void maybeDecodeDataToContent(const String& requestId);
146
    void addCachedResource(const String& requestId, CachedResource*);
148
    void addCachedResource(const String& requestId, CachedResource*);
147
    void addResourceSharedBuffer(const String& requestId, RefPtr<SharedBuffer>&&, const String& textEncodingName);
149
    void addResourceSharedBuffer(const String& requestId, RefPtr<FragmentedSharedBuffer>&&, const String& textEncodingName);
148
    ResourceData const* data(const String& requestId);
150
    ResourceData const* data(const String& requestId);
149
    ResourceData const* dataForURL(const String& url);
151
    ResourceData const* dataForURL(const String& url);
150
    Vector<String> removeCachedResource(CachedResource*);
152
    Vector<String> removeCachedResource(CachedResource*);
- a/Source/WebCore/inspector/agents/InspectorNetworkAgent.cpp -5 / +5 lines
Lines 1140-1146 void InspectorNetworkAgent::interceptRequest(ResourceLoader& loader, Function<vo a/Source/WebCore/inspector/agents/InspectorNetworkAgent.cpp_sec1
1140
    m_frontendDispatcher->requestIntercepted(requestId, buildObjectForResourceRequest(loader.request()));
1140
    m_frontendDispatcher->requestIntercepted(requestId, buildObjectForResourceRequest(loader.request()));
1141
}
1141
}
1142
1142
1143
void InspectorNetworkAgent::interceptResponse(const ResourceResponse& response, ResourceLoaderIdentifier identifier, CompletionHandler<void(const ResourceResponse&, RefPtr<SharedBuffer>)>&& handler)
1143
void InspectorNetworkAgent::interceptResponse(const ResourceResponse& response, ResourceLoaderIdentifier identifier, CompletionHandler<void(const ResourceResponse&, RefPtr<FragmentedSharedBuffer>)>&& handler)
1144
{
1144
{
1145
    ASSERT(m_enabled);
1145
    ASSERT(m_enabled);
1146
    ASSERT(m_interceptionEnabled);
1146
    ASSERT(m_interceptionEnabled);
Lines 1243-1249 Protocol::ErrorStringOr<void> InspectorNetworkAgent::interceptWithResponse(const a/Source/WebCore/inspector/agents/InspectorNetworkAgent.cpp_sec2
1243
        overrideResponse.setHTTPHeaderField(HTTPHeaderName::ContentType, overrideResponse.mimeType());
1243
        overrideResponse.setHTTPHeaderField(HTTPHeaderName::ContentType, overrideResponse.mimeType());
1244
    }
1244
    }
1245
1245
1246
    RefPtr<SharedBuffer> overrideData;
1246
    RefPtr<FragmentedSharedBuffer> overrideData;
1247
    if (base64Encoded) {
1247
    if (base64Encoded) {
1248
        auto buffer = base64Decode(content);
1248
        auto buffer = base64Decode(content);
1249
        if (!buffer)
1249
        if (!buffer)
Lines 1271-1277 Protocol::ErrorStringOr<void> InspectorNetworkAgent::interceptRequestWithRespons a/Source/WebCore/inspector/agents/InspectorNetworkAgent.cpp_sec3
1271
    if (loader->reachedTerminalState())
1271
    if (loader->reachedTerminalState())
1272
        return makeUnexpected("Unable to fulfill request, it has already been processed"_s);
1272
        return makeUnexpected("Unable to fulfill request, it has already been processed"_s);
1273
1273
1274
    RefPtr<SharedBuffer> data;
1274
    RefPtr<FragmentedSharedBuffer> data;
1275
    if (base64Encoded) {
1275
    if (base64Encoded) {
1276
        auto buffer = base64Decode(content);
1276
        auto buffer = base64Decode(content);
1277
        if (!buffer)
1277
        if (!buffer)
Lines 1407-1418 bool InspectorNetworkAgent::cachedResourceContent(CachedResource& resource, Stri a/Source/WebCore/inspector/agents/InspectorNetworkAgent.cpp_sec4
1407
        if (InspectorNetworkAgent::shouldTreatAsText(resource.mimeType())) {
1407
        if (InspectorNetworkAgent::shouldTreatAsText(resource.mimeType())) {
1408
            auto decoder = InspectorNetworkAgent::createTextDecoder(resource.mimeType(), resource.response().textEncodingName());
1408
            auto decoder = InspectorNetworkAgent::createTextDecoder(resource.mimeType(), resource.response().textEncodingName());
1409
            *base64Encoded = false;
1409
            *base64Encoded = false;
1410
            *result = decoder->decodeAndFlush(buffer->data(), buffer->size());
1410
            *result = decoder->decodeAndFlush(buffer->makeContiguous()->data(), buffer->size());
1411
            return true;
1411
            return true;
1412
        }
1412
        }
1413
1413
1414
        *base64Encoded = true;
1414
        *base64Encoded = true;
1415
        *result = base64EncodeToString(buffer->data(), buffer->size());
1415
        *result = base64EncodeToString(buffer->makeContiguous()->data(), buffer->size());
1416
        return true;
1416
        return true;
1417
    }
1417
    }
1418
}
1418
}
- a/Source/WebCore/inspector/agents/InspectorNetworkAgent.h -4 / +4 lines
Lines 123-129 public: a/Source/WebCore/inspector/agents/InspectorNetworkAgent.h_sec1
123
    bool willIntercept(const ResourceRequest&);
123
    bool willIntercept(const ResourceRequest&);
124
    bool shouldInterceptRequest(const ResourceRequest&);
124
    bool shouldInterceptRequest(const ResourceRequest&);
125
    bool shouldInterceptResponse(const ResourceResponse&);
125
    bool shouldInterceptResponse(const ResourceResponse&);
126
    void interceptResponse(const ResourceResponse&, ResourceLoaderIdentifier, CompletionHandler<void(const ResourceResponse&, RefPtr<SharedBuffer>)>&&);
126
    void interceptResponse(const ResourceResponse&, ResourceLoaderIdentifier, CompletionHandler<void(const ResourceResponse&, RefPtr<FragmentedSharedBuffer>)>&&);
127
    void interceptRequest(ResourceLoader&, Function<void(const ResourceRequest&)>&&);
127
    void interceptRequest(ResourceLoader&, Function<void(const ResourceRequest&)>&&);
128
128
129
    void searchOtherRequests(const JSC::Yarr::RegularExpression&, Ref<JSON::ArrayOf<Inspector::Protocol::Page::SearchResult>>&);
129
    void searchOtherRequests(const JSC::Yarr::RegularExpression&, Ref<JSON::ArrayOf<Inspector::Protocol::Page::SearchResult>>&);
Lines 185-191 private: a/Source/WebCore/inspector/agents/InspectorNetworkAgent.h_sec2
185
        WTF_MAKE_NONCOPYABLE(PendingInterceptResponse);
185
        WTF_MAKE_NONCOPYABLE(PendingInterceptResponse);
186
        WTF_MAKE_FAST_ALLOCATED;
186
        WTF_MAKE_FAST_ALLOCATED;
187
    public:
187
    public:
188
        PendingInterceptResponse(const ResourceResponse& originalResponse, CompletionHandler<void(const ResourceResponse&, RefPtr<SharedBuffer>)>&& completionHandler)
188
        PendingInterceptResponse(const ResourceResponse& originalResponse, CompletionHandler<void(const ResourceResponse&, RefPtr<FragmentedSharedBuffer>)>&& completionHandler)
189
            : m_originalResponse(originalResponse)
189
            : m_originalResponse(originalResponse)
190
            , m_completionHandler(WTFMove(completionHandler))
190
            , m_completionHandler(WTFMove(completionHandler))
191
        { }
191
        { }
Lines 202-208 private: a/Source/WebCore/inspector/agents/InspectorNetworkAgent.h_sec3
202
            respond(m_originalResponse, nullptr);
202
            respond(m_originalResponse, nullptr);
203
        }
203
        }
204
204
205
        void respond(const ResourceResponse& response, RefPtr<SharedBuffer> data)
205
        void respond(const ResourceResponse& response, RefPtr<FragmentedSharedBuffer> data)
206
        {
206
        {
207
            ASSERT(!m_responded);
207
            ASSERT(!m_responded);
208
            if (m_responded)
208
            if (m_responded)
Lines 215-221 private: a/Source/WebCore/inspector/agents/InspectorNetworkAgent.h_sec4
215
215
216
    private:
216
    private:
217
        ResourceResponse m_originalResponse;
217
        ResourceResponse m_originalResponse;
218
        CompletionHandler<void(const ResourceResponse&, RefPtr<SharedBuffer>)> m_completionHandler;
218
        CompletionHandler<void(const ResourceResponse&, RefPtr<FragmentedSharedBuffer>)> m_completionHandler;
219
        bool m_responded { false };
219
        bool m_responded { false };
220
    };
220
    };
221
221
- a/Source/WebCore/inspector/agents/InspectorPageAgent.cpp -5 / +5 lines
Lines 100-114 static bool decodeBuffer(const uint8_t* buffer, unsigned size, const String& tex a/Source/WebCore/inspector/agents/InspectorPageAgent.cpp_sec1
100
100
101
bool InspectorPageAgent::mainResourceContent(Frame* frame, bool withBase64Encode, String* result)
101
bool InspectorPageAgent::mainResourceContent(Frame* frame, bool withBase64Encode, String* result)
102
{
102
{
103
    RefPtr<SharedBuffer> buffer = frame->loader().documentLoader()->mainResourceData();
103
    RefPtr<FragmentedSharedBuffer> buffer = frame->loader().documentLoader()->mainResourceData();
104
    if (!buffer)
104
    if (!buffer)
105
        return false;
105
        return false;
106
    return InspectorPageAgent::dataContent(buffer->data(), buffer->size(), frame->document()->encoding(), withBase64Encode, result);
106
    return InspectorPageAgent::dataContent(buffer->makeContiguous()->data(), buffer->size(), frame->document()->encoding(), withBase64Encode, result);
107
}
107
}
108
108
109
bool InspectorPageAgent::sharedBufferContent(RefPtr<SharedBuffer>&& buffer, const String& textEncodingName, bool withBase64Encode, String* result)
109
bool InspectorPageAgent::sharedBufferContent(RefPtr<FragmentedSharedBuffer>&& buffer, const String& textEncodingName, bool withBase64Encode, String* result)
110
{
110
{
111
    return dataContent(buffer ? buffer->data() : nullptr, buffer ? buffer->size() : 0, textEncodingName, withBase64Encode, result);
111
    return dataContent(buffer ? buffer->makeContiguous()->data() : nullptr, buffer ? buffer->size() : 0, textEncodingName, withBase64Encode, result);
112
}
112
}
113
113
114
bool InspectorPageAgent::dataContent(const uint8_t* data, unsigned size, const String& textEncodingName, bool withBase64Encode, String* result)
114
bool InspectorPageAgent::dataContent(const uint8_t* data, unsigned size, const String& textEncodingName, bool withBase64Encode, String* result)
Lines 156-162 void InspectorPageAgent::resourceContent(Protocol::ErrorString& errorString, Fra a/Source/WebCore/inspector/agents/InspectorPageAgent.cpp_sec2
156
    if (!loader)
156
    if (!loader)
157
        return;
157
        return;
158
158
159
    RefPtr<SharedBuffer> buffer;
159
    RefPtr<FragmentedSharedBuffer> buffer;
160
    bool success = false;
160
    bool success = false;
161
    if (equalIgnoringFragmentIdentifier(url, loader->url())) {
161
    if (equalIgnoringFragmentIdentifier(url, loader->url())) {
162
        *base64Encoded = false;
162
        *base64Encoded = false;
- a/Source/WebCore/inspector/agents/InspectorPageAgent.h -2 / +2 lines
Lines 49-55 class InspectorClient; a/Source/WebCore/inspector/agents/InspectorPageAgent.h_sec1
49
class InspectorOverlay;
49
class InspectorOverlay;
50
class Page;
50
class Page;
51
class RenderObject;
51
class RenderObject;
52
class SharedBuffer;
52
class FragmentedSharedBuffer;
53
53
54
class InspectorPageAgent final : public InspectorAgentBase, public Inspector::PageBackendDispatcherHandler {
54
class InspectorPageAgent final : public InspectorAgentBase, public Inspector::PageBackendDispatcherHandler {
55
    WTF_MAKE_NONCOPYABLE(InspectorPageAgent);
55
    WTF_MAKE_NONCOPYABLE(InspectorPageAgent);
Lines 75-81 public: a/Source/WebCore/inspector/agents/InspectorPageAgent.h_sec2
75
        OtherResource,
75
        OtherResource,
76
    };
76
    };
77
77
78
    static bool sharedBufferContent(RefPtr<SharedBuffer>&&, const String& textEncodingName, bool withBase64Encode, String* result);
78
    static bool sharedBufferContent(RefPtr<FragmentedSharedBuffer>&&, const String& textEncodingName, bool withBase64Encode, String* result);
79
    static Vector<CachedResource*> cachedResourcesForFrame(Frame*);
79
    static Vector<CachedResource*> cachedResourcesForFrame(Frame*);
80
    static void resourceContent(Inspector::Protocol::ErrorString&, Frame*, const URL&, String* result, bool* base64Encoded);
80
    static void resourceContent(Inspector::Protocol::ErrorString&, Frame*, const URL&, String* result, bool* base64Encoded);
81
    static String sourceMapURLForResource(CachedResource*);
81
    static String sourceMapURLForResource(CachedResource*);
- a/Source/WebCore/loader/ContentFilter.cpp -2 / +2 lines
Lines 233-239 void ContentFilter::deliverResourceData(CachedResource& resource) a/Source/WebCore/loader/ContentFilter.cpp_sec1
233
    ASSERT(m_state == State::Allowed);
233
    ASSERT(m_state == State::Allowed);
234
    ASSERT(resource.dataBufferingPolicy() == DataBufferingPolicy::BufferData);
234
    ASSERT(resource.dataBufferingPolicy() == DataBufferingPolicy::BufferData);
235
    if (auto* resourceBuffer = resource.resourceBuffer())
235
    if (auto* resourceBuffer = resource.resourceBuffer())
236
        m_client.dataReceivedThroughContentFilter(resourceBuffer->data(), resourceBuffer->size());
236
        m_client.dataReceivedThroughContentFilter(resourceBuffer->makeContiguous()->data(), resourceBuffer->size());
237
}
237
}
238
238
239
static const URL& blockedPageURL()
239
static const URL& blockedPageURL()
Lines 276-282 void ContentFilter::handleProvisionalLoadFailure(const ResourceError& error) a/Source/WebCore/loader/ContentFilter.cpp_sec2
276
{
276
{
277
    ASSERT(willHandleProvisionalLoadFailure(error));
277
    ASSERT(willHandleProvisionalLoadFailure(error));
278
278
279
    RefPtr<SharedBuffer> replacementData { m_blockingContentFilter->replacementData() };
279
    RefPtr<FragmentedSharedBuffer> replacementData { m_blockingContentFilter->replacementData() };
280
    ResourceResponse response { URL(), "text/html"_s, static_cast<long long>(replacementData->size()), "UTF-8"_s };
280
    ResourceResponse response { URL(), "text/html"_s, static_cast<long long>(replacementData->size()), "UTF-8"_s };
281
    SubstituteData substituteData { WTFMove(replacementData), error.failingURL(), response, SubstituteData::SessionHistoryVisibility::Hidden };
281
    SubstituteData substituteData { WTFMove(replacementData), error.failingURL(), response, SubstituteData::SessionHistoryVisibility::Hidden };
282
    SetForScope<bool> loadingBlockedPage { m_isLoadingBlockedPage, true };
282
    SetForScope<bool> loadingBlockedPage { m_isLoadingBlockedPage, true };
- a/Source/WebCore/loader/DocumentLoader.cpp -8 / +8 lines
Lines 211-217 DocumentLoader::~DocumentLoader() a/Source/WebCore/loader/DocumentLoader.cpp_sec1
211
#endif
211
#endif
212
}
212
}
213
213
214
RefPtr<SharedBuffer> DocumentLoader::mainResourceData() const
214
RefPtr<FragmentedSharedBuffer> DocumentLoader::mainResourceData() const
215
{
215
{
216
    if (m_substituteData.isValid())
216
    if (m_substituteData.isValid())
217
        return m_substituteData.content()->copy();
217
        return m_substituteData.content()->copy();
Lines 1608-1618 bool DocumentLoader::maybeCreateArchive() a/Source/WebCore/loader/DocumentLoader.cpp_sec2
1608
    addAllArchiveResources(*m_archive);
1608
    addAllArchiveResources(*m_archive);
1609
    ASSERT(m_archive->mainResource());
1609
    ASSERT(m_archive->mainResource());
1610
    auto& mainResource = *m_archive->mainResource();
1610
    auto& mainResource = *m_archive->mainResource();
1611
    m_parsedArchiveData = &mainResource.data();
1611
    m_parsedArchiveData = mainResource.data().makeContiguous();
1612
    m_writer.setMIMEType(mainResource.mimeType());
1612
    m_writer.setMIMEType(mainResource.mimeType());
1613
1613
1614
    ASSERT(m_frame->document());
1614
    ASSERT(m_frame->document());
1615
    commitData(mainResource.data().data(), mainResource.data().size());
1615
    commitData(m_parsedArchiveData->data(), mainResource.data().size());
1616
    return true;
1616
    return true;
1617
#endif
1617
#endif
1618
}
1618
}
Lines 1671-1677 ArchiveResource* DocumentLoader::archiveResourceForURL(const URL& url) const a/Source/WebCore/loader/DocumentLoader.cpp_sec3
1671
1671
1672
RefPtr<ArchiveResource> DocumentLoader::mainResource() const
1672
RefPtr<ArchiveResource> DocumentLoader::mainResource() const
1673
{
1673
{
1674
    RefPtr<SharedBuffer> data = mainResourceData();
1674
    RefPtr<FragmentedSharedBuffer> data = mainResourceData();
1675
    if (!data)
1675
    if (!data)
1676
        data = SharedBuffer::create();
1676
        data = SharedBuffer::create();
1677
    auto& response = this->response();
1677
    auto& response = this->response();
Lines 2255-2262 void DocumentLoader::maybeFinishLoadingMultipartContent() a/Source/WebCore/loader/DocumentLoader.cpp_sec4
2255
2255
2256
    frameLoader()->setupForReplace();
2256
    frameLoader()->setupForReplace();
2257
    m_committed = false;
2257
    m_committed = false;
2258
    RefPtr<SharedBuffer> resourceData = mainResourceData();
2258
    RefPtr<FragmentedSharedBuffer> resourceData = mainResourceData();
2259
    commitLoad(resourceData->data(), resourceData->size());
2259
    commitLoad(resourceData->makeContiguous()->data(), resourceData->size());
2260
}
2260
}
2261
2261
2262
void DocumentLoader::startIconLoading()
2262
void DocumentLoader::startIconLoading()
Lines 2292-2298 void DocumentLoader::startIconLoading() a/Source/WebCore/loader/DocumentLoader.cpp_sec5
2292
    m_frame->loader().client().getLoadDecisionForIcons(iconDecisions);
2292
    m_frame->loader().client().getLoadDecisionForIcons(iconDecisions);
2293
}
2293
}
2294
2294
2295
void DocumentLoader::didGetLoadDecisionForIcon(bool decision, uint64_t loadIdentifier, CompletionHandler<void(SharedBuffer*)>&& completionHandler)
2295
void DocumentLoader::didGetLoadDecisionForIcon(bool decision, uint64_t loadIdentifier, CompletionHandler<void(FragmentedSharedBuffer*)>&& completionHandler)
2296
{
2296
{
2297
    auto icon = m_iconsPendingLoadDecision.take(loadIdentifier);
2297
    auto icon = m_iconsPendingLoadDecision.take(loadIdentifier);
2298
2298
Lines 2313-2319 void DocumentLoader::didGetLoadDecisionForIcon(bool decision, uint64_t loadIdent a/Source/WebCore/loader/DocumentLoader.cpp_sec6
2313
    rawIconLoader->startLoading();
2313
    rawIconLoader->startLoading();
2314
}
2314
}
2315
2315
2316
void DocumentLoader::finishedLoadingIcon(IconLoader& loader, SharedBuffer* buffer)
2316
void DocumentLoader::finishedLoadingIcon(IconLoader& loader, FragmentedSharedBuffer* buffer)
2317
{
2317
{
2318
    // If the DocumentLoader has detached from its frame, all icon loads should have already been cancelled.
2318
    // If the DocumentLoader has detached from its frame, all icon loads should have already been cancelled.
2319
    ASSERT(m_frame);
2319
    ASSERT(m_frame);
- a/Source/WebCore/loader/DocumentLoader.h -5 / +6 lines
Lines 75-80 class ArchiveResourceCollection; a/Source/WebCore/loader/DocumentLoader.h_sec1
75
class CachedRawResource;
75
class CachedRawResource;
76
class CachedResourceLoader;
76
class CachedResourceLoader;
77
class ContentFilter;
77
class ContentFilter;
78
class SharedBuffer;
78
struct CustomHeaderFields;
79
struct CustomHeaderFields;
79
class FormState;
80
class FormState;
80
class Frame;
81
class Frame;
Lines 83-89 class IconLoader; a/Source/WebCore/loader/DocumentLoader.h_sec2
83
class Page;
84
class Page;
84
class PreviewConverter;
85
class PreviewConverter;
85
class ResourceLoader;
86
class ResourceLoader;
86
class SharedBuffer;
87
class FragmentedSharedBuffer;
87
class SWClientConnection;
88
class SWClientConnection;
88
class SubresourceLoader;
89
class SubresourceLoader;
89
class SubstituteResource;
90
class SubstituteResource;
Lines 171-177 public: a/Source/WebCore/loader/DocumentLoader.h_sec3
171
172
172
    WEBCORE_EXPORT FrameLoader* frameLoader() const;
173
    WEBCORE_EXPORT FrameLoader* frameLoader() const;
173
    WEBCORE_EXPORT SubresourceLoader* mainResourceLoader() const;
174
    WEBCORE_EXPORT SubresourceLoader* mainResourceLoader() const;
174
    WEBCORE_EXPORT RefPtr<SharedBuffer> mainResourceData() const;
175
    WEBCORE_EXPORT RefPtr<FragmentedSharedBuffer> mainResourceData() const;
175
    
176
    
176
    DocumentWriter& writer() const { return m_writer; }
177
    DocumentWriter& writer() const { return m_writer; }
177
178
Lines 392-399 public: a/Source/WebCore/loader/DocumentLoader.h_sec4
392
#endif
393
#endif
393
394
394
    void startIconLoading();
395
    void startIconLoading();
395
    WEBCORE_EXPORT void didGetLoadDecisionForIcon(bool decision, uint64_t loadIdentifier, CompletionHandler<void(SharedBuffer*)>&&);
396
    WEBCORE_EXPORT void didGetLoadDecisionForIcon(bool decision, uint64_t loadIdentifier, CompletionHandler<void(FragmentedSharedBuffer*)>&&);
396
    void finishedLoadingIcon(IconLoader&, SharedBuffer*);
397
    void finishedLoadingIcon(IconLoader&, FragmentedSharedBuffer*);
397
398
398
    const Vector<LinkIcon>& linkIcons() const { return m_linkIcons; }
399
    const Vector<LinkIcon>& linkIcons() const { return m_linkIcons; }
399
400
Lines 621-627 private: a/Source/WebCore/loader/DocumentLoader.h_sec5
621
    bool m_waitingForNavigationPolicy { false };
622
    bool m_waitingForNavigationPolicy { false };
622
623
623
    HashMap<uint64_t, LinkIcon> m_iconsPendingLoadDecision;
624
    HashMap<uint64_t, LinkIcon> m_iconsPendingLoadDecision;
624
    HashMap<std::unique_ptr<IconLoader>, CompletionHandler<void(SharedBuffer*)>> m_iconLoaders;
625
    HashMap<std::unique_ptr<IconLoader>, CompletionHandler<void(FragmentedSharedBuffer*)>> m_iconLoaders;
625
    Vector<LinkIcon> m_linkIcons;
626
    Vector<LinkIcon> m_linkIcons;
626
627
627
#if ENABLE(APPLICATION_MANIFEST)
628
#if ENABLE(APPLICATION_MANIFEST)
- a/Source/WebCore/loader/FrameLoader.h -1 / +1 lines
Lines 59-64 class CachedFrameBase; a/Source/WebCore/loader/FrameLoader.h_sec1
59
class CachedPage;
59
class CachedPage;
60
class CachedResource;
60
class CachedResource;
61
class Chrome;
61
class Chrome;
62
class SharedBuffer;
62
class DOMWrapperWorld;
63
class DOMWrapperWorld;
63
class Document;
64
class Document;
64
class DocumentLoader;
65
class DocumentLoader;
Lines 76-82 class ResourceError; a/Source/WebCore/loader/FrameLoader.h_sec2
76
class ResourceRequest;
77
class ResourceRequest;
77
class ResourceResponse;
78
class ResourceResponse;
78
class SerializedScriptValue;
79
class SerializedScriptValue;
79
class SharedBuffer;
80
class SubstituteData;
80
class SubstituteData;
81
81
82
enum class CachePolicy : uint8_t;
82
enum class CachePolicy : uint8_t;
- a/Source/WebCore/loader/FrameLoaderClient.h -1 / +1 lines
Lines 98-104 class ResourceHandle; a/Source/WebCore/loader/FrameLoaderClient.h_sec1
98
class ResourceRequest;
98
class ResourceRequest;
99
class ResourceResponse;
99
class ResourceResponse;
100
class SecurityOrigin;
100
class SecurityOrigin;
101
class SharedBuffer;
101
class FragmentedSharedBuffer;
102
class SubstituteData;
102
class SubstituteData;
103
class Widget;
103
class Widget;
104
104
- a/Source/WebCore/loader/LoaderStrategy.h -1 / +1 lines
Lines 51-57 class ResourceLoader; a/Source/WebCore/loader/LoaderStrategy.h_sec1
51
class ResourceRequest;
51
class ResourceRequest;
52
class ResourceResponse;
52
class ResourceResponse;
53
class SecurityOrigin;
53
class SecurityOrigin;
54
class SharedBuffer;
54
class FragmentedSharedBuffer;
55
class SubresourceLoader;
55
class SubresourceLoader;
56
56
57
struct FetchOptions;
57
struct FetchOptions;
- a/Source/WebCore/loader/NetscapePlugInStreamLoader.cpp -2 / +2 lines
Lines 146-157 void NetscapePlugInStreamLoader::didReceiveData(const uint8_t* data, unsigned le a/Source/WebCore/loader/NetscapePlugInStreamLoader.cpp_sec1
146
    didReceiveDataOrBuffer(data, length, nullptr, encodedDataLength, dataPayloadType);
146
    didReceiveDataOrBuffer(data, length, nullptr, encodedDataLength, dataPayloadType);
147
}
147
}
148
148
149
void NetscapePlugInStreamLoader::didReceiveBuffer(Ref<SharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
149
void NetscapePlugInStreamLoader::didReceiveBuffer(Ref<FragmentedSharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
150
{
150
{
151
    didReceiveDataOrBuffer(nullptr, 0, WTFMove(buffer), encodedDataLength, dataPayloadType);
151
    didReceiveDataOrBuffer(nullptr, 0, WTFMove(buffer), encodedDataLength, dataPayloadType);
152
}
152
}
153
153
154
void NetscapePlugInStreamLoader::didReceiveDataOrBuffer(const uint8_t* data, int length, RefPtr<SharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
154
void NetscapePlugInStreamLoader::didReceiveDataOrBuffer(const uint8_t* data, int length, RefPtr<FragmentedSharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
155
{
155
{
156
    Ref<NetscapePlugInStreamLoader> protectedThis(*this);
156
    Ref<NetscapePlugInStreamLoader> protectedThis(*this);
157
157
- a/Source/WebCore/loader/NetscapePlugInStreamLoader.h -2 / +2 lines
Lines 63-69 private: a/Source/WebCore/loader/NetscapePlugInStreamLoader.h_sec1
63
    void willSendRequest(ResourceRequest&&, const ResourceResponse& redirectResponse, CompletionHandler<void(ResourceRequest&&)>&& callback) override;
63
    void willSendRequest(ResourceRequest&&, const ResourceResponse& redirectResponse, CompletionHandler<void(ResourceRequest&&)>&& callback) override;
64
    void didReceiveResponse(const ResourceResponse&, CompletionHandler<void()>&& policyCompletionHandler) override;
64
    void didReceiveResponse(const ResourceResponse&, CompletionHandler<void()>&& policyCompletionHandler) override;
65
    void didReceiveData(const uint8_t*, unsigned, long long encodedDataLength, DataPayloadType) override;
65
    void didReceiveData(const uint8_t*, unsigned, long long encodedDataLength, DataPayloadType) override;
66
    void didReceiveBuffer(Ref<SharedBuffer>&&, long long encodedDataLength, DataPayloadType) override;
66
    void didReceiveBuffer(Ref<FragmentedSharedBuffer>&&, long long encodedDataLength, DataPayloadType) override;
67
    void didFinishLoading(const NetworkLoadMetrics&) override;
67
    void didFinishLoading(const NetworkLoadMetrics&) override;
68
    void didFail(const ResourceError&) override;
68
    void didFail(const ResourceError&) override;
69
69
Lines 74-80 private: a/Source/WebCore/loader/NetscapePlugInStreamLoader.h_sec2
74
    void willCancel(const ResourceError&) override;
74
    void willCancel(const ResourceError&) override;
75
    void didCancel(const ResourceError&) override;
75
    void didCancel(const ResourceError&) override;
76
76
77
    void didReceiveDataOrBuffer(const uint8_t*, int, RefPtr<SharedBuffer>&&, long long encodedDataLength, DataPayloadType);
77
    void didReceiveDataOrBuffer(const uint8_t*, int, RefPtr<FragmentedSharedBuffer>&&, long long encodedDataLength, DataPayloadType);
78
78
79
    void notifyDone();
79
    void notifyDone();
80
80
- a/Source/WebCore/loader/ResourceCryptographicDigest.cpp -1 / +1 lines
Lines 155-161 ResourceCryptographicDigest cryptographicDigestForBytes(ResourceCryptographicDig a/Source/WebCore/loader/ResourceCryptographicDigest.cpp_sec1
155
    return { algorithm, cryptoDigest->computeHash() };
155
    return { algorithm, cryptoDigest->computeHash() };
156
}
156
}
157
157
158
ResourceCryptographicDigest cryptographicDigestForSharedBuffer(ResourceCryptographicDigest::Algorithm algorithm, const SharedBuffer* buffer)
158
ResourceCryptographicDigest cryptographicDigestForSharedBuffer(ResourceCryptographicDigest::Algorithm algorithm, const FragmentedSharedBuffer* buffer)
159
{
159
{
160
    auto cryptoDigest = PAL::CryptoDigest::create(toCryptoDigestAlgorithm(algorithm));
160
    auto cryptoDigest = PAL::CryptoDigest::create(toCryptoDigestAlgorithm(algorithm));
161
    if (buffer) {
161
    if (buffer) {
- a/Source/WebCore/loader/ResourceCryptographicDigest.h -2 / +2 lines
Lines 34-40 a/Source/WebCore/loader/ResourceCryptographicDigest.h_sec1
34
namespace WebCore {
34
namespace WebCore {
35
35
36
class CachedResource;
36
class CachedResource;
37
class SharedBuffer;
37
class FragmentedSharedBuffer;
38
38
39
struct ResourceCryptographicDigest {
39
struct ResourceCryptographicDigest {
40
    enum class Algorithm {
40
    enum class Algorithm {
Lines 75-81 std::optional<EncodedResourceCryptographicDigest> parseEncodedCryptographicDiges a/Source/WebCore/loader/ResourceCryptographicDigest.h_sec2
75
75
76
std::optional<ResourceCryptographicDigest> decodeEncodedResourceCryptographicDigest(const EncodedResourceCryptographicDigest&);
76
std::optional<ResourceCryptographicDigest> decodeEncodedResourceCryptographicDigest(const EncodedResourceCryptographicDigest&);
77
77
78
ResourceCryptographicDigest cryptographicDigestForSharedBuffer(ResourceCryptographicDigest::Algorithm, const SharedBuffer*);
78
ResourceCryptographicDigest cryptographicDigestForSharedBuffer(ResourceCryptographicDigest::Algorithm, const FragmentedSharedBuffer*);
79
ResourceCryptographicDigest cryptographicDigestForBytes(ResourceCryptographicDigest::Algorithm, const void* bytes, size_t length);
79
ResourceCryptographicDigest cryptographicDigestForBytes(ResourceCryptographicDigest::Algorithm, const void* bytes, size_t length);
80
80
81
}
81
}
- a/Source/WebCore/loader/ResourceLoader.cpp -19 / +20 lines
Lines 76-81 DEFINE_ALLOCATOR_WITH_HEAP_IDENTIFIER(ResourceLoader); a/Source/WebCore/loader/ResourceLoader.cpp_sec1
76
ResourceLoader::ResourceLoader(Frame& frame, ResourceLoaderOptions options)
76
ResourceLoader::ResourceLoader(Frame& frame, ResourceLoaderOptions options)
77
    : m_frame { &frame }
77
    : m_frame { &frame }
78
    , m_documentLoader { frame.loader().activeDocumentLoader() }
78
    , m_documentLoader { frame.loader().activeDocumentLoader() }
79
    , m_resourceData { makeUniqueRef<SharedBufferBuilder>() }
79
    , m_defersLoading { options.defersLoadingPolicy == DefersLoadingPolicy::AllowDefersLoading && frame.page()->defersLoading() }
80
    , m_defersLoading { options.defersLoadingPolicy == DefersLoadingPolicy::AllowDefersLoading && frame.page()->defersLoading() }
80
    , m_options { options }
81
    , m_options { options }
81
{
82
{
Lines 118-124 void ResourceLoader::releaseResources() a/Source/WebCore/loader/ResourceLoader.cpp_sec2
118
119
119
    m_identifier = { };
120
    m_identifier = { };
120
121
121
    m_resourceData = nullptr;
122
    m_resourceData->reset();
122
    m_deferredRequest = ResourceRequest();
123
    m_deferredRequest = ResourceRequest();
123
}
124
}
124
125
Lines 189-195 void ResourceLoader::init(ResourceRequest&& clientRequest, CompletionHandler<voi a/Source/WebCore/loader/ResourceLoader.cpp_sec3
189
    });
190
    });
190
}
191
}
191
192
192
void ResourceLoader::deliverResponseAndData(const ResourceResponse& response, RefPtr<SharedBuffer>&& buffer)
193
void ResourceLoader::deliverResponseAndData(const ResourceResponse& response, RefPtr<FragmentedSharedBuffer>&& buffer)
193
{
194
{
194
    didReceiveResponse(response, [this, protectedThis = Ref { *this }, buffer = WTFMove(buffer)]() mutable {
195
    didReceiveResponse(response, [this, protectedThis = Ref { *this }, buffer = WTFMove(buffer)]() mutable {
195
        if (reachedTerminalState())
196
        if (reachedTerminalState())
Lines 318-324 void ResourceLoader::setDataBufferingPolicy(DataBufferingPolicy dataBufferingPol a/Source/WebCore/loader/ResourceLoader.cpp_sec4
318
319
319
    // Reset any already buffered data
320
    // Reset any already buffered data
320
    if (dataBufferingPolicy == DataBufferingPolicy::DoNotBufferData)
321
    if (dataBufferingPolicy == DataBufferingPolicy::DoNotBufferData)
321
        m_resourceData = nullptr;
322
        m_resourceData->reset();
322
}
323
}
323
324
324
void ResourceLoader::willSwitchToSubstituteResource()
325
void ResourceLoader::willSwitchToSubstituteResource()
Lines 329-357 void ResourceLoader::willSwitchToSubstituteResource() a/Source/WebCore/loader/ResourceLoader.cpp_sec5
329
        m_handle->cancel();
330
        m_handle->cancel();
330
}
331
}
331
332
332
void ResourceLoader::addDataOrBuffer(const uint8_t* data, unsigned length, SharedBuffer* buffer, DataPayloadType dataPayloadType)
333
void ResourceLoader::addDataOrBuffer(const uint8_t* data, unsigned length, FragmentedSharedBuffer* buffer, DataPayloadType dataPayloadType)
333
{
334
{
334
    if (m_options.dataBufferingPolicy == DataBufferingPolicy::DoNotBufferData)
335
    if (m_options.dataBufferingPolicy == DataBufferingPolicy::DoNotBufferData)
335
        return;
336
        return;
336
337
337
    if (!m_resourceData || dataPayloadType == DataPayloadWholeResource) {
338
    if (dataPayloadType == DataPayloadWholeResource)
338
        if (buffer)
339
        m_resourceData->reset();
339
            m_resourceData = buffer;
340
340
        else
341
            m_resourceData = SharedBuffer::create(data, length);
342
        return;
343
    }
344
    
345
    if (buffer)
341
    if (buffer)
346
        m_resourceData->append(*buffer);
342
        m_resourceData->append(*buffer);
347
    else
343
    else
348
        m_resourceData->append(data, length);
344
        m_resourceData->append(data, length);
349
}
345
}
350
346
347
const FragmentedSharedBuffer* ResourceLoader::resourceData() const
348
{
349
    return m_resourceData->get().get();
350
}
351
351
void ResourceLoader::clearResourceData()
352
void ResourceLoader::clearResourceData()
352
{
353
{
353
    if (m_resourceData)
354
    if (!m_resourceData->isNull())
354
        m_resourceData->clear();
355
        m_resourceData->empty();
355
}
356
}
356
357
357
bool ResourceLoader::isSubresourceLoader() const
358
bool ResourceLoader::isSubresourceLoader() const
Lines 551-564 void ResourceLoader::didReceiveData(const uint8_t* data, unsigned length, long l a/Source/WebCore/loader/ResourceLoader.cpp_sec6
551
    didReceiveDataOrBuffer(data, length, nullptr, encodedDataLength, dataPayloadType);
552
    didReceiveDataOrBuffer(data, length, nullptr, encodedDataLength, dataPayloadType);
552
}
553
}
553
554
554
void ResourceLoader::didReceiveBuffer(Ref<SharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
555
void ResourceLoader::didReceiveBuffer(Ref<FragmentedSharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
555
{
556
{
556
    didReceiveDataOrBuffer(nullptr, 0, WTFMove(buffer), encodedDataLength, dataPayloadType);
557
    didReceiveDataOrBuffer(nullptr, 0, WTFMove(buffer), encodedDataLength, dataPayloadType);
557
}
558
}
558
559
559
void ResourceLoader::didReceiveDataOrBuffer(const uint8_t* data, unsigned length, RefPtr<SharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
560
void ResourceLoader::didReceiveDataOrBuffer(const uint8_t* data, unsigned length, RefPtr<FragmentedSharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
560
{
561
{
561
    // This method should only get data+length *OR* a SharedBuffer.
562
    // This method should only get data+length *OR* a FragmentedSharedBuffer.
562
    ASSERT(!buffer || (!data && !length));
563
    ASSERT(!buffer || (!data && !length));
563
564
564
    // Protect this in this delegate method since the additional processing can do
565
    // Protect this in this delegate method since the additional processing can do
Lines 571-577 void ResourceLoader::didReceiveDataOrBuffer(const uint8_t* data, unsigned length a/Source/WebCore/loader/ResourceLoader.cpp_sec7
571
    // However, with today's computers and networking speeds, this won't happen in practice.
572
    // However, with today's computers and networking speeds, this won't happen in practice.
572
    // Could be an issue with a giant local file.
573
    // Could be an issue with a giant local file.
573
    if (m_options.sendLoadCallbacks == SendCallbackPolicy::SendCallbacks && m_frame)
574
    if (m_options.sendLoadCallbacks == SendCallbackPolicy::SendCallbacks && m_frame)
574
        frameLoader()->notifier().didReceiveData(this, buffer ? buffer->data() : data, buffer ? buffer->size() : length, static_cast<int>(encodedDataLength));
575
        frameLoader()->notifier().didReceiveData(this, buffer ? buffer->makeContiguous()->data() : data, buffer ? buffer->size() : length, static_cast<int>(encodedDataLength));
575
}
576
}
576
577
577
void ResourceLoader::didFinishLoading(const NetworkLoadMetrics& networkLoadMetrics)
578
void ResourceLoader::didFinishLoading(const NetworkLoadMetrics& networkLoadMetrics)
Lines 735-741 void ResourceLoader::didReceiveData(ResourceHandle*, const uint8_t* data, unsign a/Source/WebCore/loader/ResourceLoader.cpp_sec8
735
    didReceiveData(data, length, encodedDataLength, DataPayloadBytes);
736
    didReceiveData(data, length, encodedDataLength, DataPayloadBytes);
736
}
737
}
737
738
738
void ResourceLoader::didReceiveBuffer(ResourceHandle*, Ref<SharedBuffer>&& buffer, int encodedDataLength)
739
void ResourceLoader::didReceiveBuffer(ResourceHandle*, Ref<FragmentedSharedBuffer>&& buffer, int encodedDataLength)
739
{
740
{
740
    didReceiveBuffer(WTFMove(buffer), encodedDataLength, DataPayloadBytes);
741
    didReceiveBuffer(WTFMove(buffer), encodedDataLength, DataPayloadBytes);
741
}
742
}
- a/Source/WebCore/loader/ResourceLoader.h -7 / +10 lines
Lines 36-41 a/Source/WebCore/loader/ResourceLoader.h_sec1
36
#include "ResourceRequest.h"
36
#include "ResourceRequest.h"
37
#include "ResourceResponse.h"
37
#include "ResourceResponse.h"
38
#include <wtf/Forward.h>
38
#include <wtf/Forward.h>
39
#include <wtf/UniqueRef.h>
39
#include <wtf/WeakPtr.h>
40
#include <wtf/WeakPtr.h>
40
41
41
#if ENABLE(CONTENT_EXTENSIONS)
42
#if ENABLE(CONTENT_EXTENSIONS)
Lines 55-60 class Frame; a/Source/WebCore/loader/ResourceLoader.h_sec2
55
class FrameLoader;
56
class FrameLoader;
56
class LegacyPreviewLoader;
57
class LegacyPreviewLoader;
57
class NetworkLoadMetrics;
58
class NetworkLoadMetrics;
59
class FragmentedSharedBuffer;
60
class SharedBufferBuilder;
58
61
59
DECLARE_ALLOCATOR_WITH_HEAP_IDENTIFIER(ResourceLoader);
62
DECLARE_ALLOCATOR_WITH_HEAP_IDENTIFIER(ResourceLoader);
60
class ResourceLoader : public CanMakeWeakPtr<ResourceLoader>, public RefCounted<ResourceLoader>, protected ResourceHandleClient {
63
class ResourceLoader : public CanMakeWeakPtr<ResourceLoader>, public RefCounted<ResourceLoader>, protected ResourceHandleClient {
Lines 66-72 public: a/Source/WebCore/loader/ResourceLoader.h_sec3
66
69
67
    virtual void init(ResourceRequest&&, CompletionHandler<void(bool)>&&);
70
    virtual void init(ResourceRequest&&, CompletionHandler<void(bool)>&&);
68
71
69
    void deliverResponseAndData(const ResourceResponse&, RefPtr<SharedBuffer>&&);
72
    void deliverResponseAndData(const ResourceResponse&, RefPtr<FragmentedSharedBuffer>&&);
70
73
71
#if PLATFORM(IOS_FAMILY)
74
#if PLATFORM(IOS_FAMILY)
72
    virtual void startLoading()
75
    virtual void startLoading()
Lines 98-104 public: a/Source/WebCore/loader/ResourceLoader.h_sec4
98
    virtual void releaseResources();
101
    virtual void releaseResources();
99
    const ResourceResponse& response() const { return m_response; }
102
    const ResourceResponse& response() const { return m_response; }
100
103
101
    SharedBuffer* resourceData() const { return m_resourceData.get(); }
104
    const FragmentedSharedBuffer* resourceData() const;
102
    void clearResourceData();
105
    void clearResourceData();
103
    
106
    
104
    virtual bool isSubresourceLoader() const;
107
    virtual bool isSubresourceLoader() const;
Lines 107-113 public: a/Source/WebCore/loader/ResourceLoader.h_sec5
107
    virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent);
110
    virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent);
108
    virtual void didReceiveResponse(const ResourceResponse&, CompletionHandler<void()>&& policyCompletionHandler);
111
    virtual void didReceiveResponse(const ResourceResponse&, CompletionHandler<void()>&& policyCompletionHandler);
109
    virtual void didReceiveData(const uint8_t*, unsigned, long long encodedDataLength, DataPayloadType);
112
    virtual void didReceiveData(const uint8_t*, unsigned, long long encodedDataLength, DataPayloadType);
110
    virtual void didReceiveBuffer(Ref<SharedBuffer>&&, long long encodedDataLength, DataPayloadType);
113
    virtual void didReceiveBuffer(Ref<FragmentedSharedBuffer>&&, long long encodedDataLength, DataPayloadType);
111
    virtual void didFinishLoading(const NetworkLoadMetrics&);
114
    virtual void didFinishLoading(const NetworkLoadMetrics&);
112
    virtual void didFail(const ResourceError&);
115
    virtual void didFail(const ResourceError&);
113
116
Lines 166-172 protected: a/Source/WebCore/loader/ResourceLoader.h_sec6
166
169
167
    bool wasCancelled() const { return m_cancellationStatus >= Cancelled; }
170
    bool wasCancelled() const { return m_cancellationStatus >= Cancelled; }
168
171
169
    void didReceiveDataOrBuffer(const uint8_t*, unsigned, RefPtr<SharedBuffer>&&, long long encodedDataLength, DataPayloadType);
172
    void didReceiveDataOrBuffer(const uint8_t*, unsigned, RefPtr<FragmentedSharedBuffer>&&, long long encodedDataLength, DataPayloadType);
170
    
173
    
171
    void setReferrerPolicy(ReferrerPolicy referrerPolicy) { m_options.referrerPolicy = referrerPolicy; }
174
    void setReferrerPolicy(ReferrerPolicy referrerPolicy) { m_options.referrerPolicy = referrerPolicy; }
172
    ReferrerPolicy referrerPolicy() const { return m_options.referrerPolicy; }
175
    ReferrerPolicy referrerPolicy() const { return m_options.referrerPolicy; }
Lines 191-197 private: a/Source/WebCore/loader/ResourceLoader.h_sec7
191
    virtual void willCancel(const ResourceError&) = 0;
194
    virtual void willCancel(const ResourceError&) = 0;
192
    virtual void didCancel(const ResourceError&) = 0;
195
    virtual void didCancel(const ResourceError&) = 0;
193
196
194
    void addDataOrBuffer(const uint8_t*, unsigned, SharedBuffer*, DataPayloadType);
197
    void addDataOrBuffer(const uint8_t*, unsigned, FragmentedSharedBuffer*, DataPayloadType);
195
    void loadDataURL();
198
    void loadDataURL();
196
    void finishNetworkLoad();
199
    void finishNetworkLoad();
197
200
Lines 202-208 private: a/Source/WebCore/loader/ResourceLoader.h_sec8
202
    void didReceiveResponseAsync(ResourceHandle*, ResourceResponse&&, CompletionHandler<void()>&&) override;
205
    void didReceiveResponseAsync(ResourceHandle*, ResourceResponse&&, CompletionHandler<void()>&&) override;
203
    void willSendRequestAsync(ResourceHandle*, ResourceRequest&&, ResourceResponse&&, CompletionHandler<void(ResourceRequest&&)>&&) override;
206
    void willSendRequestAsync(ResourceHandle*, ResourceRequest&&, ResourceResponse&&, CompletionHandler<void(ResourceRequest&&)>&&) override;
204
    void didReceiveData(ResourceHandle*, const uint8_t*, unsigned, int encodedDataLength) override;
207
    void didReceiveData(ResourceHandle*, const uint8_t*, unsigned, int encodedDataLength) override;
205
    void didReceiveBuffer(ResourceHandle*, Ref<SharedBuffer>&&, int encodedDataLength) override;
208
    void didReceiveBuffer(ResourceHandle*, Ref<FragmentedSharedBuffer>&&, int encodedDataLength) override;
206
    void didFinishLoading(ResourceHandle*, const NetworkLoadMetrics&) override;
209
    void didFinishLoading(ResourceHandle*, const NetworkLoadMetrics&) override;
207
    void didFail(ResourceHandle*, const ResourceError&) override;
210
    void didFail(ResourceHandle*, const ResourceError&) override;
208
    void wasBlocked(ResourceHandle*) override;
211
    void wasBlocked(ResourceHandle*) override;
Lines 227-233 private: a/Source/WebCore/loader/ResourceLoader.h_sec9
227
230
228
    ResourceRequest m_request;
231
    ResourceRequest m_request;
229
    ResourceRequest m_originalRequest; // Before redirects.
232
    ResourceRequest m_originalRequest; // Before redirects.
230
    RefPtr<SharedBuffer> m_resourceData;
233
    UniqueRef<SharedBufferBuilder> m_resourceData;
231
    
234
    
232
    ResourceLoaderIdentifier m_identifier;
235
    ResourceLoaderIdentifier m_identifier;
233
236
- a/Source/WebCore/loader/SubresourceLoader.cpp -3 / +3 lines
Lines 530-536 void SubresourceLoader::didReceiveData(const uint8_t* data, unsigned length, lon a/Source/WebCore/loader/SubresourceLoader.cpp_sec1
530
    didReceiveDataOrBuffer(data, length, nullptr, encodedDataLength, dataPayloadType);
530
    didReceiveDataOrBuffer(data, length, nullptr, encodedDataLength, dataPayloadType);
531
}
531
}
532
532
533
void SubresourceLoader::didReceiveBuffer(Ref<SharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
533
void SubresourceLoader::didReceiveBuffer(Ref<FragmentedSharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
534
{
534
{
535
#if USE(QUICK_LOOK)
535
#if USE(QUICK_LOOK)
536
    if (auto previewLoader = m_previewLoader.get()) {
536
    if (auto previewLoader = m_previewLoader.get()) {
Lines 542-548 void SubresourceLoader::didReceiveBuffer(Ref<SharedBuffer>&& buffer, long long e a/Source/WebCore/loader/SubresourceLoader.cpp_sec2
542
    didReceiveDataOrBuffer(nullptr, 0, WTFMove(buffer), encodedDataLength, dataPayloadType);
542
    didReceiveDataOrBuffer(nullptr, 0, WTFMove(buffer), encodedDataLength, dataPayloadType);
543
}
543
}
544
544
545
void SubresourceLoader::didReceiveDataOrBuffer(const uint8_t* data, int length, RefPtr<SharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
545
void SubresourceLoader::didReceiveDataOrBuffer(const uint8_t* data, int length, RefPtr<FragmentedSharedBuffer>&& buffer, long long encodedDataLength, DataPayloadType dataPayloadType)
546
{
546
{
547
    ASSERT(m_resource);
547
    ASSERT(m_resource);
548
548
Lines 561-567 void SubresourceLoader::didReceiveDataOrBuffer(const uint8_t* data, int length, a/Source/WebCore/loader/SubresourceLoader.cpp_sec3
561
        if (auto* resourceData = this->resourceData())
561
        if (auto* resourceData = this->resourceData())
562
            m_resource->updateBuffer(*resourceData);
562
            m_resource->updateBuffer(*resourceData);
563
        else
563
        else
564
            m_resource->updateData(buffer ? buffer->data() : data, buffer ? buffer->size() : length);
564
            m_resource->updateData(buffer ? buffer->makeContiguous()->data() : data, buffer ? buffer->size() : length);
565
    }
565
    }
566
}
566
}
567
567
- a/Source/WebCore/loader/SubresourceLoader.h -2 / +2 lines
Lines 74-80 private: a/Source/WebCore/loader/SubresourceLoader.h_sec1
74
    void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent) override;
74
    void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent) override;
75
    void didReceiveResponse(const ResourceResponse&, CompletionHandler<void()>&& policyCompletionHandler) override;
75
    void didReceiveResponse(const ResourceResponse&, CompletionHandler<void()>&& policyCompletionHandler) override;
76
    void didReceiveData(const uint8_t*, unsigned, long long encodedDataLength, DataPayloadType) override;
76
    void didReceiveData(const uint8_t*, unsigned, long long encodedDataLength, DataPayloadType) override;
77
    void didReceiveBuffer(Ref<SharedBuffer>&&, long long encodedDataLength, DataPayloadType) override;
77
    void didReceiveBuffer(Ref<FragmentedSharedBuffer>&&, long long encodedDataLength, DataPayloadType) override;
78
    void didFinishLoading(const NetworkLoadMetrics&) override;
78
    void didFinishLoading(const NetworkLoadMetrics&) override;
79
    void didFail(const ResourceError&) override;
79
    void didFail(const ResourceError&) override;
80
    void willCancel(const ResourceError&) override;
80
    void willCancel(const ResourceError&) override;
Lines 92-98 private: a/Source/WebCore/loader/SubresourceLoader.h_sec2
92
    Expected<void, String> checkResponseCrossOriginAccessControl(const ResourceResponse&);
92
    Expected<void, String> checkResponseCrossOriginAccessControl(const ResourceResponse&);
93
    Expected<void, String> checkRedirectionCrossOriginAccessControl(const ResourceRequest& previousRequest, const ResourceResponse&, ResourceRequest& newRequest);
93
    Expected<void, String> checkRedirectionCrossOriginAccessControl(const ResourceRequest& previousRequest, const ResourceResponse&, ResourceRequest& newRequest);
94
94
95
    void didReceiveDataOrBuffer(const uint8_t*, int, RefPtr<SharedBuffer>&&, long long encodedDataLength, DataPayloadType);
95
    void didReceiveDataOrBuffer(const uint8_t*, int, RefPtr<FragmentedSharedBuffer>&&, long long encodedDataLength, DataPayloadType);
96
96
97
    void notifyDone(LoadCompletionType);
97
    void notifyDone(LoadCompletionType);
98
98
- a/Source/WebCore/loader/SubstituteData.h -3 / +3 lines
Lines 43-49 namespace WebCore { a/Source/WebCore/loader/SubstituteData.h_sec1
43
        {
43
        {
44
        }
44
        }
45
45
46
        SubstituteData(RefPtr<SharedBuffer>&& content, const URL& failingURL, const ResourceResponse& response, SessionHistoryVisibility shouldRevealToSessionHistory)
46
        SubstituteData(RefPtr<FragmentedSharedBuffer>&& content, const URL& failingURL, const ResourceResponse& response, SessionHistoryVisibility shouldRevealToSessionHistory)
47
            : m_content(WTFMove(content))
47
            : m_content(WTFMove(content))
48
            , m_failingURL(failingURL)
48
            , m_failingURL(failingURL)
49
            , m_response(response)
49
            , m_response(response)
Lines 54-67 namespace WebCore { a/Source/WebCore/loader/SubstituteData.h_sec2
54
        bool isValid() const { return m_content != nullptr; }
54
        bool isValid() const { return m_content != nullptr; }
55
        bool shouldRevealToSessionHistory() const { return m_shouldRevealToSessionHistory == SessionHistoryVisibility::Visible; }
55
        bool shouldRevealToSessionHistory() const { return m_shouldRevealToSessionHistory == SessionHistoryVisibility::Visible; }
56
56
57
        const SharedBuffer* content() const { return m_content.get(); }
57
        const FragmentedSharedBuffer* content() const { return m_content.get(); }
58
        const String& mimeType() const { return m_response.mimeType(); }
58
        const String& mimeType() const { return m_response.mimeType(); }
59
        const String& textEncoding() const { return m_response.textEncodingName(); }
59
        const String& textEncoding() const { return m_response.textEncodingName(); }
60
        const URL& failingURL() const { return m_failingURL; }
60
        const URL& failingURL() const { return m_failingURL; }
61
        const ResourceResponse& response() const { return m_response; }
61
        const ResourceResponse& response() const { return m_response; }
62
        
62
        
63
    private:
63
    private:
64
        RefPtr<SharedBuffer> m_content;
64
        RefPtr<FragmentedSharedBuffer> m_content;
65
        URL m_failingURL;
65
        URL m_failingURL;
66
        ResourceResponse m_response;
66
        ResourceResponse m_response;
67
        SessionHistoryVisibility m_shouldRevealToSessionHistory { SessionHistoryVisibility::Hidden };
67
        SessionHistoryVisibility m_shouldRevealToSessionHistory { SessionHistoryVisibility::Hidden };
- a/Source/WebCore/loader/SubstituteResource.h -4 / +6 lines
Lines 37-48 public: a/Source/WebCore/loader/SubstituteResource.h_sec1
37
37
38
    const URL& url() const { return m_url; }
38
    const URL& url() const { return m_url; }
39
    const ResourceResponse& response() const { return m_response; }
39
    const ResourceResponse& response() const { return m_response; }
40
    SharedBuffer& data() const { return static_reference_cast<SharedBuffer>(m_data); }
40
    FragmentedSharedBuffer& data() const { return static_reference_cast<FragmentedSharedBuffer>(Ref { *m_data.get() }); }
41
    void append(const uint8_t* data, int length) { m_data.append(data, length); }
42
    void clear() { m_data.empty(); }
41
43
42
    virtual void deliver(ResourceLoader& loader) { loader.deliverResponseAndData(m_response, m_data->copy()); }
44
    virtual void deliver(ResourceLoader& loader) { loader.deliverResponseAndData(m_response, m_data.copy()); }
43
45
44
protected:
46
protected:
45
    SubstituteResource(URL&& url, ResourceResponse&& response, Ref<SharedBuffer>&& data)
47
    SubstituteResource(URL&& url, ResourceResponse&& response, Ref<FragmentedSharedBuffer>&& data)
46
        : m_url(WTFMove(url))
48
        : m_url(WTFMove(url))
47
        , m_response(WTFMove(response))
49
        , m_response(WTFMove(response))
48
        , m_data(WTFMove(data))
50
        , m_data(WTFMove(data))
Lines 52-58 protected: a/Source/WebCore/loader/SubstituteResource.h_sec2
52
private:
54
private:
53
    URL m_url;
55
    URL m_url;
54
    ResourceResponse m_response;
56
    ResourceResponse m_response;
55
    Ref<SharedBuffer> m_data;
57
    SharedBufferBuilder m_data;
56
};
58
};
57
59
58
} // namespace WebCore
60
} // namespace WebCore
- a/Source/WebCore/loader/appcache/ApplicationCacheGroup.cpp -1 / +1 lines
Lines 605-611 void ApplicationCacheGroup::didFinishLoadingManifest() a/Source/WebCore/loader/appcache/ApplicationCacheGroup.cpp_sec1
605
        }
605
        }
606
    }
606
    }
607
    
607
    
608
    auto manifest = parseApplicationCacheManifest(m_manifestURL, m_manifestResource->response().mimeType(), m_manifestResource->data().data(), m_manifestResource->data().size());
608
    auto manifest = parseApplicationCacheManifest(m_manifestURL, m_manifestResource->response().mimeType(), m_manifestResource->data().makeContiguous()->data(), m_manifestResource->data().size());
609
    if (!manifest) {
609
    if (!manifest) {
610
        // At the time of this writing, lack of "CACHE MANIFEST" signature is the only reason for parseManifest to fail.
610
        // At the time of this writing, lack of "CACHE MANIFEST" signature is the only reason for parseManifest to fail.
611
        m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, "Application Cache manifest could not be parsed. Does it start with CACHE MANIFEST?"_s);
611
        m_frame->document()->addConsoleMessage(MessageSource::AppCache, MessageLevel::Error, "Application Cache manifest could not be parsed. Does it start with CACHE MANIFEST?"_s);
- a/Source/WebCore/loader/appcache/ApplicationCacheHost.cpp -6 / +2 lines
Lines 255-264 URL ApplicationCacheHost::createFileURL(const String& path) a/Source/WebCore/loader/appcache/ApplicationCacheHost.cpp_sec1
255
255
256
static inline RefPtr<SharedBuffer> bufferFromResource(ApplicationCacheResource& resource)
256
static inline RefPtr<SharedBuffer> bufferFromResource(ApplicationCacheResource& resource)
257
{
257
{
258
    // FIXME: Clients probably do not need a copy of the SharedBuffer.
259
    // Remove the call to copy() once we ensure SharedBuffer will not be modified.
260
    if (resource.path().isEmpty())
258
    if (resource.path().isEmpty())
261
        return resource.data().copy();
259
        return resource.data().makeContiguous();
262
    return SharedBuffer::createWithContentsOfFile(resource.path());
260
    return SharedBuffer::createWithContentsOfFile(resource.path());
263
}
261
}
264
262
Lines 290-298 void ApplicationCacheHost::maybeLoadFallbackSynchronously(const ResourceRequest& a/Source/WebCore/loader/appcache/ApplicationCacheHost.cpp_sec2
290
        ApplicationCacheResource* resource;
288
        ApplicationCacheResource* resource;
291
        if (getApplicationCacheFallbackResource(request, resource)) {
289
        if (getApplicationCacheFallbackResource(request, resource)) {
292
            response = resource->response();
290
            response = resource->response();
293
            // FIXME: Clients proably do not need a copy of the SharedBuffer.
291
            data = resource->data().makeContiguous();
294
            // Remove the call to copy() once we ensure SharedBuffer will not be modified.
295
            data = resource->data().copy();
296
        }
292
        }
297
    }
293
    }
298
}
294
}
- a/Source/WebCore/loader/appcache/ApplicationCacheHost.h -1 / +1 lines
Lines 42-47 class ApplicationCache; a/Source/WebCore/loader/appcache/ApplicationCacheHost.h_sec1
42
class ApplicationCacheGroup;
42
class ApplicationCacheGroup;
43
class ApplicationCacheResource;
43
class ApplicationCacheResource;
44
class ApplicationCacheStorage;
44
class ApplicationCacheStorage;
45
class SharedBuffer;
45
class DOMApplicationCache;
46
class DOMApplicationCache;
46
class DocumentLoader;
47
class DocumentLoader;
47
class Frame;
48
class Frame;
Lines 49-55 class ResourceError; a/Source/WebCore/loader/appcache/ApplicationCacheHost.h_sec2
49
class ResourceLoader;
50
class ResourceLoader;
50
class ResourceRequest;
51
class ResourceRequest;
51
class ResourceResponse;
52
class ResourceResponse;
52
class SharedBuffer;
53
class SubstituteData;
53
class SubstituteData;
54
54
55
class ApplicationCacheHost {
55
class ApplicationCacheHost {
- a/Source/WebCore/loader/appcache/ApplicationCacheResource.cpp -3 / +3 lines
Lines 29-35 a/Source/WebCore/loader/appcache/ApplicationCacheResource.cpp_sec1
29
29
30
namespace WebCore {
30
namespace WebCore {
31
31
32
Ref<ApplicationCacheResource> ApplicationCacheResource::create(const URL& url, const ResourceResponse& response, unsigned type, RefPtr<SharedBuffer>&& buffer, const String& path)
32
Ref<ApplicationCacheResource> ApplicationCacheResource::create(const URL& url, const ResourceResponse& response, unsigned type, RefPtr<FragmentedSharedBuffer>&& buffer, const String& path)
33
{
33
{
34
    ASSERT(!url.hasFragmentIdentifier());
34
    ASSERT(!url.hasFragmentIdentifier());
35
    if (!buffer)
35
    if (!buffer)
Lines 40-46 Ref<ApplicationCacheResource> ApplicationCacheResource::create(const URL& url, c a/Source/WebCore/loader/appcache/ApplicationCacheResource.cpp_sec2
40
    return adoptRef(*new ApplicationCacheResource(URL { url }, WTFMove(resourceResponse), type, buffer.releaseNonNull(), path));
40
    return adoptRef(*new ApplicationCacheResource(URL { url }, WTFMove(resourceResponse), type, buffer.releaseNonNull(), path));
41
}
41
}
42
42
43
ApplicationCacheResource::ApplicationCacheResource(URL&& url, ResourceResponse&& response, unsigned type, Ref<SharedBuffer>&& data, const String& path)
43
ApplicationCacheResource::ApplicationCacheResource(URL&& url, ResourceResponse&& response, unsigned type, Ref<FragmentedSharedBuffer>&& data, const String& path)
44
    : SubstituteResource(WTFMove(url), WTFMove(response), WTFMove(data))
44
    : SubstituteResource(WTFMove(url), WTFMove(response), WTFMove(data))
45
    , m_type(type)
45
    , m_type(type)
46
    , m_storageID(0)
46
    , m_storageID(0)
Lines 51-57 ApplicationCacheResource::ApplicationCacheResource(URL&& url, ResourceResponse&& a/Source/WebCore/loader/appcache/ApplicationCacheResource.cpp_sec3
51
51
52
void ApplicationCacheResource::deliver(ResourceLoader& loader)
52
void ApplicationCacheResource::deliver(ResourceLoader& loader)
53
{
53
{
54
    loader.deliverResponseAndData(response(), m_path.isEmpty() ? data().copy() : SharedBuffer::createWithContentsOfFile(m_path));
54
    loader.deliverResponseAndData(response(), m_path.isEmpty() ? data().makeContiguous() : SharedBuffer::createWithContentsOfFile(m_path));
55
}
55
}
56
56
57
void ApplicationCacheResource::addType(unsigned type) 
57
void ApplicationCacheResource::addType(unsigned type) 
- a/Source/WebCore/loader/appcache/ApplicationCacheResource.h -2 / +2 lines
Lines 40-46 public: a/Source/WebCore/loader/appcache/ApplicationCacheResource.h_sec1
40
        Fallback = 1 << 4
40
        Fallback = 1 << 4
41
    };
41
    };
42
42
43
    static Ref<ApplicationCacheResource> create(const URL&, const ResourceResponse&, unsigned type, RefPtr<SharedBuffer>&& = SharedBuffer::create(), const String& path = String());
43
    static Ref<ApplicationCacheResource> create(const URL&, const ResourceResponse&, unsigned type, RefPtr<FragmentedSharedBuffer>&& = SharedBuffer::create(), const String& path = String());
44
44
45
    unsigned type() const { return m_type; }
45
    unsigned type() const { return m_type; }
46
    void addType(unsigned type);
46
    void addType(unsigned type);
Lines 58-64 public: a/Source/WebCore/loader/appcache/ApplicationCacheResource.h_sec2
58
#endif
58
#endif
59
    
59
    
60
private:
60
private:
61
    ApplicationCacheResource(URL&&, ResourceResponse&&, unsigned type, Ref<SharedBuffer>&&, const String& path);
61
    ApplicationCacheResource(URL&&, ResourceResponse&&, unsigned type, Ref<FragmentedSharedBuffer>&&, const String& path);
62
62
63
    void deliver(ResourceLoader&) override;
63
    void deliver(ResourceLoader&) override;
64
64
- a/Source/WebCore/loader/appcache/ApplicationCacheResourceLoader.cpp -1 / +1 lines
Lines 101-107 void ApplicationCacheResourceLoader::responseReceived(CachedResource& resource, a/Source/WebCore/loader/appcache/ApplicationCacheResourceLoader.cpp_sec1
101
101
102
void ApplicationCacheResourceLoader::dataReceived(CachedResource&, const uint8_t* data, int length)
102
void ApplicationCacheResourceLoader::dataReceived(CachedResource&, const uint8_t* data, int length)
103
{
103
{
104
    m_applicationCacheResource->data().append(data, length);
104
    m_applicationCacheResource->append(data, length);
105
}
105
}
106
106
107
void ApplicationCacheResourceLoader::redirectReceived(CachedResource&, ResourceRequest&& newRequest, const ResourceResponse&, CompletionHandler<void(ResourceRequest&&)>&& callback)
107
void ApplicationCacheResourceLoader::redirectReceived(CachedResource&, ResourceRequest&& newRequest, const ResourceResponse&, CompletionHandler<void(ResourceRequest&&)>&& callback)
- a/Source/WebCore/loader/appcache/ApplicationCacheStorage.cpp -5 / +4 lines
Lines 783-789 bool ApplicationCacheStorage::store(ApplicationCacheResource* resource, unsigned a/Source/WebCore/loader/appcache/ApplicationCacheStorage.cpp_sec1
783
    auto dataStatement = m_database.prepareStatement("INSERT INTO CacheResourceData (data, path) VALUES (?, ?)"_s);
783
    auto dataStatement = m_database.prepareStatement("INSERT INTO CacheResourceData (data, path) VALUES (?, ?)"_s);
784
    if (!dataStatement)
784
    if (!dataStatement)
785
        return false;
785
        return false;
786
    
787
786
788
    String fullPath;
787
    String fullPath;
789
    if (!resource->path().isEmpty())
788
    if (!resource->path().isEmpty())
Lines 815-821 bool ApplicationCacheStorage::store(ApplicationCacheResource* resource, unsigned a/Source/WebCore/loader/appcache/ApplicationCacheStorage.cpp_sec2
815
        dataStatement->bindText(2, path);
814
        dataStatement->bindText(2, path);
816
    } else {
815
    } else {
817
        if (resource->data().size())
816
        if (resource->data().size())
818
            dataStatement->bindBlob(1, resource->data());
817
            dataStatement->bindBlob(1, resource->data().makeContiguous().get());
819
    }
818
    }
820
    
819
    
821
    if (!dataStatement->executeCommand()) {
820
    if (!dataStatement->executeCommand()) {
Lines 873-884 bool ApplicationCacheStorage::store(ApplicationCacheResource* resource, unsigned a/Source/WebCore/loader/appcache/ApplicationCacheStorage.cpp_sec3
873
    
872
    
874
    if (!executeStatement(entryStatement.value()))
873
    if (!executeStatement(entryStatement.value()))
875
        return false;
874
        return false;
876
    
875
877
    // Did we successfully write the resource data to a file? If so,
876
    // Did we successfully write the resource data to a file? If so,
878
    // release the resource's data and free up a potentially large amount
877
    // release the resource's data and free up a potentially large amount
879
    // of memory:
878
    // of memory:
880
    if (!fullPath.isEmpty())
879
    if (!fullPath.isEmpty())
881
        resource->data().clear();
880
        resource->clear();
882
881
883
    resource->setStorageID(resourceId);
882
    resource->setStorageID(resourceId);
884
    return true;
883
    return true;
Lines 1273-1279 bool ApplicationCacheStorage::shouldStoreResourceAsFlatFile(ApplicationCacheReso a/Source/WebCore/loader/appcache/ApplicationCacheStorage.cpp_sec4
1273
    return startsWithLettersIgnoringASCIICase(type, "audio/") || startsWithLettersIgnoringASCIICase(type, "video/");
1272
    return startsWithLettersIgnoringASCIICase(type, "audio/") || startsWithLettersIgnoringASCIICase(type, "video/");
1274
}
1273
}
1275
    
1274
    
1276
bool ApplicationCacheStorage::writeDataToUniqueFileInDirectory(SharedBuffer& data, const String& directory, String& path, const String& fileExtension)
1275
bool ApplicationCacheStorage::writeDataToUniqueFileInDirectory(FragmentedSharedBuffer& data, const String& directory, String& path, const String& fileExtension)
1277
{
1276
{
1278
    String fullPath;
1277
    String fullPath;
1279
    
1278
    
- a/Source/WebCore/loader/appcache/ApplicationCacheStorage.h -2 / +2 lines
Lines 39-45 class ApplicationCacheGroup; a/Source/WebCore/loader/appcache/ApplicationCacheStorage.h_sec1
39
class ApplicationCacheHost;
39
class ApplicationCacheHost;
40
class ApplicationCacheResource;
40
class ApplicationCacheResource;
41
class SecurityOrigin;
41
class SecurityOrigin;
42
class SharedBuffer;
42
class FragmentedSharedBuffer;
43
template<typename> class StorageIDJournal;
43
template<typename> class StorageIDJournal;
44
44
45
class ApplicationCacheStorage : public RefCounted<ApplicationCacheStorage> {
45
class ApplicationCacheStorage : public RefCounted<ApplicationCacheStorage> {
Lines 122-128 private: a/Source/WebCore/loader/appcache/ApplicationCacheStorage.h_sec2
122
    bool ensureOriginRecord(const SecurityOrigin*);
122
    bool ensureOriginRecord(const SecurityOrigin*);
123
    static bool shouldStoreResourceAsFlatFile(ApplicationCacheResource*);
123
    static bool shouldStoreResourceAsFlatFile(ApplicationCacheResource*);
124
    void deleteTables();
124
    void deleteTables();
125
    bool writeDataToUniqueFileInDirectory(SharedBuffer&, const String& directory, String& outFilename, const String& fileExtension);
125
    bool writeDataToUniqueFileInDirectory(FragmentedSharedBuffer&, const String& directory, String& outFilename, const String& fileExtension);
126
126
127
    void loadManifestHostHashes();
127
    void loadManifestHostHashes();
128
    
128
    
- a/Source/WebCore/loader/archive/ArchiveFactory.cpp -3 / +3 lines
Lines 46-57 a/Source/WebCore/loader/archive/ArchiveFactory.cpp_sec1
46
46
47
namespace WebCore {
47
namespace WebCore {
48
48
49
typedef RefPtr<Archive> RawDataCreationFunction(const URL&, SharedBuffer&);
49
typedef RefPtr<Archive> RawDataCreationFunction(const URL&, FragmentedSharedBuffer&);
50
typedef HashMap<String, RawDataCreationFunction*, ASCIICaseInsensitiveHash> ArchiveMIMETypesMap;
50
typedef HashMap<String, RawDataCreationFunction*, ASCIICaseInsensitiveHash> ArchiveMIMETypesMap;
51
51
52
// The create functions in the archive classes return RefPtr to concrete subclasses
52
// The create functions in the archive classes return RefPtr to concrete subclasses
53
// of Archive. This adaptor makes the functions have a uniform return type.
53
// of Archive. This adaptor makes the functions have a uniform return type.
54
template<typename ArchiveClass> static RefPtr<Archive> archiveFactoryCreate(const URL& url, SharedBuffer& buffer)
54
template<typename ArchiveClass> static RefPtr<Archive> archiveFactoryCreate(const URL& url, FragmentedSharedBuffer& buffer)
55
{
55
{
56
    return ArchiveClass::create(url, buffer);
56
    return ArchiveClass::create(url, buffer);
57
}
57
}
Lines 83-89 bool ArchiveFactory::isArchiveMIMEType(const String& mimeType) a/Source/WebCore/loader/archive/ArchiveFactory.cpp_sec2
83
    return !mimeType.isEmpty() && archiveMIMETypes().contains(mimeType);
83
    return !mimeType.isEmpty() && archiveMIMETypes().contains(mimeType);
84
}
84
}
85
85
86
RefPtr<Archive> ArchiveFactory::create(const URL& url, SharedBuffer* data, const String& mimeType)
86
RefPtr<Archive> ArchiveFactory::create(const URL& url, FragmentedSharedBuffer* data, const String& mimeType)
87
{
87
{
88
    if (!data)
88
    if (!data)
89
        return nullptr;
89
        return nullptr;
- a/Source/WebCore/loader/archive/ArchiveFactory.h -2 / +2 lines
Lines 34-45 a/Source/WebCore/loader/archive/ArchiveFactory.h_sec1
34
34
35
namespace WebCore {
35
namespace WebCore {
36
36
37
class SharedBuffer;
37
class FragmentedSharedBuffer;
38
38
39
class ArchiveFactory {
39
class ArchiveFactory {
40
public:
40
public:
41
    static bool isArchiveMIMEType(const String&);
41
    static bool isArchiveMIMEType(const String&);
42
    static RefPtr<Archive> create(const URL&, SharedBuffer* data, const String& mimeType);
42
    static RefPtr<Archive> create(const URL&, FragmentedSharedBuffer* data, const String& mimeType);
43
    static void registerKnownArchiveMIMETypes(HashSet<String, ASCIICaseInsensitiveHash>&);
43
    static void registerKnownArchiveMIMETypes(HashSet<String, ASCIICaseInsensitiveHash>&);
44
};
44
};
45
45
- a/Source/WebCore/loader/archive/ArchiveResource.cpp -3 / +3 lines
Lines 33-39 a/Source/WebCore/loader/archive/ArchiveResource.cpp_sec1
33
33
34
namespace WebCore {
34
namespace WebCore {
35
35
36
inline ArchiveResource::ArchiveResource(Ref<SharedBuffer>&& data, const URL& url, const String& mimeType, const String& textEncoding, const String& frameName, const ResourceResponse& response)
36
inline ArchiveResource::ArchiveResource(Ref<FragmentedSharedBuffer>&& data, const URL& url, const String& mimeType, const String& textEncoding, const String& frameName, const ResourceResponse& response)
37
    : SubstituteResource(URL { url }, ResourceResponse { response }, WTFMove(data))
37
    : SubstituteResource(URL { url }, ResourceResponse { response }, WTFMove(data))
38
    , m_mimeType(mimeType)
38
    , m_mimeType(mimeType)
39
    , m_textEncoding(textEncoding)
39
    , m_textEncoding(textEncoding)
Lines 42-48 inline ArchiveResource::ArchiveResource(Ref<SharedBuffer>&& data, const URL& url a/Source/WebCore/loader/archive/ArchiveResource.cpp_sec2
42
{
42
{
43
}
43
}
44
44
45
RefPtr<ArchiveResource> ArchiveResource::create(RefPtr<SharedBuffer>&& data, const URL& url, const String& mimeType, const String& textEncoding, const String& frameName, const ResourceResponse& response)
45
RefPtr<ArchiveResource> ArchiveResource::create(RefPtr<FragmentedSharedBuffer>&& data, const URL& url, const String& mimeType, const String& textEncoding, const String& frameName, const ResourceResponse& response)
46
{
46
{
47
    if (!data)
47
    if (!data)
48
        return nullptr;
48
        return nullptr;
Lines 54-60 RefPtr<ArchiveResource> ArchiveResource::create(RefPtr<SharedBuffer>&& data, con a/Source/WebCore/loader/archive/ArchiveResource.cpp_sec3
54
    return adoptRef(*new ArchiveResource(data.releaseNonNull(), url, mimeType, textEncoding, frameName, response));
54
    return adoptRef(*new ArchiveResource(data.releaseNonNull(), url, mimeType, textEncoding, frameName, response));
55
}
55
}
56
56
57
RefPtr<ArchiveResource> ArchiveResource::create(RefPtr<SharedBuffer>&& data, const URL& url, const ResourceResponse& response)
57
RefPtr<ArchiveResource> ArchiveResource::create(RefPtr<FragmentedSharedBuffer>&& data, const URL& url, const ResourceResponse& response)
58
{
58
{
59
    return create(WTFMove(data), url, response.mimeType(), response.textEncodingName(), String(), response);
59
    return create(WTFMove(data), url, response.mimeType(), response.textEncodingName(), String(), response);
60
}
60
}
- a/Source/WebCore/loader/archive/ArchiveResource.h -3 / +3 lines
Lines 34-41 namespace WebCore { a/Source/WebCore/loader/archive/ArchiveResource.h_sec1
34
34
35
class ArchiveResource : public SubstituteResource {
35
class ArchiveResource : public SubstituteResource {
36
public:
36
public:
37
    static RefPtr<ArchiveResource> create(RefPtr<SharedBuffer>&&, const URL&, const ResourceResponse&);
37
    static RefPtr<ArchiveResource> create(RefPtr<FragmentedSharedBuffer>&&, const URL&, const ResourceResponse&);
38
    WEBCORE_EXPORT static RefPtr<ArchiveResource> create(RefPtr<SharedBuffer>&&, const URL&,
38
    WEBCORE_EXPORT static RefPtr<ArchiveResource> create(RefPtr<FragmentedSharedBuffer>&&, const URL&,
39
        const String& mimeType, const String& textEncoding, const String& frameName,
39
        const String& mimeType, const String& textEncoding, const String& frameName,
40
        const ResourceResponse& = ResourceResponse());
40
        const ResourceResponse& = ResourceResponse());
41
41
Lines 47-53 public: a/Source/WebCore/loader/archive/ArchiveResource.h_sec2
47
    bool shouldIgnoreWhenUnarchiving() const { return m_shouldIgnoreWhenUnarchiving; }
47
    bool shouldIgnoreWhenUnarchiving() const { return m_shouldIgnoreWhenUnarchiving; }
48
48
49
private:
49
private:
50
    ArchiveResource(Ref<SharedBuffer>&&, const URL&, const String& mimeType, const String& textEncoding, const String& frameName, const ResourceResponse&);
50
    ArchiveResource(Ref<FragmentedSharedBuffer>&&, const URL&, const String& mimeType, const String& textEncoding, const String& frameName, const ResourceResponse&);
51
51
52
    String m_mimeType;
52
    String m_mimeType;
53
    String m_textEncoding;
53
    String m_textEncoding;
- a/Source/WebCore/loader/archive/cf/LegacyWebArchive.cpp -20 / +20 lines
Lines 90-96 RetainPtr<CFDictionaryRef> LegacyWebArchive::createPropertyListRepresentation(Ar a/Source/WebCore/loader/archive/cf/LegacyWebArchive.cpp_sec1
90
    // Resource data can be empty, but must be represented by an empty CFDataRef
90
    // Resource data can be empty, but must be represented by an empty CFDataRef
91
    auto& data = resource->data();
91
    auto& data = resource->data();
92
92
93
    CFDictionarySetValue(propertyList.get(), LegacyWebArchiveResourceDataKey, data.createCFData().get());
93
    CFDictionarySetValue(propertyList.get(), LegacyWebArchiveResourceDataKey, data.makeContiguous()->createCFData().get());
94
94
95
    // Resource URL cannot be null
95
    // Resource URL cannot be null
96
    if (auto cfURL = resource->url().string().createCFString())
96
    if (auto cfURL = resource->url().string().createCFString())
Lines 117-125 RetainPtr<CFDictionaryRef> LegacyWebArchive::createPropertyListRepresentation(Ar a/Source/WebCore/loader/archive/cf/LegacyWebArchive.cpp_sec2
117
    // Don't include the resource response for the main resource
117
    // Don't include the resource response for the main resource
118
    if (!isMainResource) {
118
    if (!isMainResource) {
119
        if (auto resourceResponseData = createPropertyListRepresentation(resource->response()))
119
        if (auto resourceResponseData = createPropertyListRepresentation(resource->response()))
120
            CFDictionarySetValue(propertyList.get(), LegacyWebArchiveResourceResponseKey, resourceResponseData.get());    
120
            CFDictionarySetValue(propertyList.get(), LegacyWebArchiveResourceResponseKey, resourceResponseData.get());
121
    }
121
    }
122
    
122
123
    return propertyList;
123
    return propertyList;
124
}
124
}
125
125
Lines 215-227 RefPtr<ArchiveResource> LegacyWebArchive::createResource(CFDictionaryRef diction a/Source/WebCore/loader/archive/cf/LegacyWebArchive.cpp_sec3
215
            LOG(Archives, "LegacyWebArchive - Resource response data is not of type CFData, cannot create invalid resource");
215
            LOG(Archives, "LegacyWebArchive - Resource response data is not of type CFData, cannot create invalid resource");
216
            return nullptr;
216
            return nullptr;
217
        }
217
        }
218
        
218
219
        auto resourceResponseVersion = static_cast<CFStringRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceResponseVersionKey));
219
        auto resourceResponseVersion = static_cast<CFStringRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveResourceResponseVersionKey));
220
        if (resourceResponseVersion && CFGetTypeID(resourceResponseVersion) != CFStringGetTypeID()) {
220
        if (resourceResponseVersion && CFGetTypeID(resourceResponseVersion) != CFStringGetTypeID()) {
221
            LOG(Archives, "LegacyWebArchive - Resource response version is not of type CFString, cannot create invalid resource");
221
            LOG(Archives, "LegacyWebArchive - Resource response version is not of type CFString, cannot create invalid resource");
222
            return nullptr;
222
            return nullptr;
223
        }
223
        }
224
        
224
225
        response = createResourceResponseFromPropertyListData(resourceResponseData, resourceResponseVersion);
225
        response = createResourceResponseFromPropertyListData(resourceResponseData, resourceResponseVersion);
226
    }
226
    }
227
227
Lines 248-270 Ref<LegacyWebArchive> LegacyWebArchive::create(Ref<ArchiveResource>&& mainResour a/Source/WebCore/loader/archive/cf/LegacyWebArchive.cpp_sec4
248
    return archive;
248
    return archive;
249
}
249
}
250
250
251
RefPtr<LegacyWebArchive> LegacyWebArchive::create(SharedBuffer& data)
251
RefPtr<LegacyWebArchive> LegacyWebArchive::create(FragmentedSharedBuffer& data)
252
{
252
{
253
    return create(URL(), data);
253
    return create(URL(), data);
254
}
254
}
255
255
256
RefPtr<LegacyWebArchive> LegacyWebArchive::create(const URL&, SharedBuffer& data)
256
RefPtr<LegacyWebArchive> LegacyWebArchive::create(const URL&, FragmentedSharedBuffer& data)
257
{
257
{
258
    LOG(Archives, "LegacyWebArchive - Creating from raw data");
258
    LOG(Archives, "LegacyWebArchive - Creating from raw data");
259
    
259
260
    Ref<LegacyWebArchive> archive = create();
260
    Ref<LegacyWebArchive> archive = create();
261
        
261
262
    RetainPtr<CFDataRef> cfData = data.createCFData();
262
    RetainPtr<CFDataRef> cfData = data.makeContiguous()->createCFData();
263
    if (!cfData)
263
    if (!cfData)
264
        return nullptr;
264
        return nullptr;
265
        
265
266
    CFErrorRef error = nullptr;
266
    CFErrorRef error = nullptr;
267
    
267
268
    RetainPtr<CFDictionaryRef> plist = adoptCF(static_cast<CFDictionaryRef>(CFPropertyListCreateWithData(0, cfData.get(), kCFPropertyListImmutable, 0, &error)));
268
    RetainPtr<CFDictionaryRef> plist = adoptCF(static_cast<CFDictionaryRef>(CFPropertyListCreateWithData(0, cfData.get(), kCFPropertyListImmutable, 0, &error)));
269
    if (!plist) {
269
    if (!plist) {
270
#ifndef NDEBUG
270
#ifndef NDEBUG
Lines 276-287 RefPtr<LegacyWebArchive> LegacyWebArchive::create(const URL&, SharedBuffer& data a/Source/WebCore/loader/archive/cf/LegacyWebArchive.cpp_sec5
276
            CFRelease(error);
276
            CFRelease(error);
277
        return nullptr;
277
        return nullptr;
278
    }
278
    }
279
    
279
280
    if (CFGetTypeID(plist.get()) != CFDictionaryGetTypeID()) {
280
    if (CFGetTypeID(plist.get()) != CFDictionaryGetTypeID()) {
281
        LOG(Archives, "LegacyWebArchive - Archive property list is not the expected CFDictionary, aborting invalid WebArchive");
281
        LOG(Archives, "LegacyWebArchive - Archive property list is not the expected CFDictionary, aborting invalid WebArchive");
282
        return nullptr;
282
        return nullptr;
283
    }
283
    }
284
    
284
285
    if (!archive->extract(plist.get()))
285
    if (!archive->extract(plist.get()))
286
        return nullptr;
286
        return nullptr;
287
287
Lines 295-301 bool LegacyWebArchive::extract(CFDictionaryRef dictionary) a/Source/WebCore/loader/archive/cf/LegacyWebArchive.cpp_sec6
295
        LOG(Archives, "LegacyWebArchive - Null root CFDictionary, aborting invalid WebArchive");
295
        LOG(Archives, "LegacyWebArchive - Null root CFDictionary, aborting invalid WebArchive");
296
        return false;
296
        return false;
297
    }
297
    }
298
    
298
299
    CFDictionaryRef mainResourceDict = static_cast<CFDictionaryRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveMainResourceKey));
299
    CFDictionaryRef mainResourceDict = static_cast<CFDictionaryRef>(CFDictionaryGetValue(dictionary, LegacyWebArchiveMainResourceKey));
300
    if (!mainResourceDict) {
300
    if (!mainResourceDict) {
301
        LOG(Archives, "LegacyWebArchive - No main resource in archive, aborting invalid WebArchive");
301
        LOG(Archives, "LegacyWebArchive - No main resource in archive, aborting invalid WebArchive");
Lines 333-339 bool LegacyWebArchive::extract(CFDictionaryRef dictionary) a/Source/WebCore/loader/archive/cf/LegacyWebArchive.cpp_sec7
333
                LOG(Archives, "LegacyWebArchive - Subresource is not expected CFDictionary, aborting invalid WebArchive");
333
                LOG(Archives, "LegacyWebArchive - Subresource is not expected CFDictionary, aborting invalid WebArchive");
334
                return false;
334
                return false;
335
            }
335
            }
336
            
336
337
            if (auto subresource = createResource(subresourceDict))
337
            if (auto subresource = createResource(subresourceDict))
338
                addSubresource(subresource.releaseNonNull());
338
                addSubresource(subresource.releaseNonNull());
339
        }
339
        }
Lines 353-359 bool LegacyWebArchive::extract(CFDictionaryRef dictionary) a/Source/WebCore/loader/archive/cf/LegacyWebArchive.cpp_sec8
353
                LOG(Archives, "LegacyWebArchive - Subframe array is not expected CFDictionary, aborting invalid WebArchive");
353
                LOG(Archives, "LegacyWebArchive - Subframe array is not expected CFDictionary, aborting invalid WebArchive");
354
                return false;
354
                return false;
355
            }
355
            }
356
            
356
357
            auto subframeArchive = create();
357
            auto subframeArchive = create();
358
            if (subframeArchive->extract(subframeDict))
358
            if (subframeArchive->extract(subframeDict))
359
                addSubframeArchive(WTFMove(subframeArchive));
359
                addSubframeArchive(WTFMove(subframeArchive));
Lines 361-367 bool LegacyWebArchive::extract(CFDictionaryRef dictionary) a/Source/WebCore/loader/archive/cf/LegacyWebArchive.cpp_sec9
361
                LOG(Archives, "LegacyWebArchive - Invalid subframe archive skipped");
361
                LOG(Archives, "LegacyWebArchive - Invalid subframe archive skipped");
362
        }
362
        }
363
    }
363
    }
364
    
364
365
    return true;
365
    return true;
366
}
366
}
367
367
Lines 506-512 RefPtr<LegacyWebArchive> LegacyWebArchive::create(const String& markupString, Fr a/Source/WebCore/loader/archive/cf/LegacyWebArchive.cpp_sec10
506
{
506
{
507
    auto& response = frame.loader().documentLoader()->response();
507
    auto& response = frame.loader().documentLoader()->response();
508
    URL responseURL = response.url();
508
    URL responseURL = response.url();
509
    
509
510
    // it's possible to have a response without a URL here
510
    // it's possible to have a response without a URL here
511
    // <rdar://problem/5454935>
511
    // <rdar://problem/5454935>
512
    if (responseURL.isNull())
512
    if (responseURL.isNull())
Lines 605-611 RefPtr<LegacyWebArchive> LegacyWebArchive::createFromSelection(Frame* frame) a/Source/WebCore/loader/archive/cf/LegacyWebArchive.cpp_sec11
605
605
606
    if (!document->isFrameSet())
606
    if (!document->isFrameSet())
607
        return archive;
607
        return archive;
608
        
608
609
    // Wrap the frameset document in an iframe so it can be pasted into
609
    // Wrap the frameset document in an iframe so it can be pasted into
610
    // another document (which will have a body or frameset of its own). 
610
    // another document (which will have a body or frameset of its own). 
611
    String iframeMarkup = "<iframe frameborder=\"no\" marginwidth=\"0\" marginheight=\"0\" width=\"98%%\" height=\"98%%\" src=\"" + frame->loader().documentLoader()->response().url().string() + "\"></iframe>";
611
    String iframeMarkup = "<iframe frameborder=\"no\" marginwidth=\"0\" marginheight=\"0\" width=\"98%%\" height=\"98%%\" src=\"" + frame->loader().documentLoader()->response().url().string() + "\"></iframe>";
- a/Source/WebCore/loader/archive/cf/LegacyWebArchive.h -2 / +2 lines
Lines 41-48 struct SimpleRange; a/Source/WebCore/loader/archive/cf/LegacyWebArchive.h_sec1
41
class LegacyWebArchive final : public Archive {
41
class LegacyWebArchive final : public Archive {
42
public:
42
public:
43
    WEBCORE_EXPORT static Ref<LegacyWebArchive> create();
43
    WEBCORE_EXPORT static Ref<LegacyWebArchive> create();
44
    WEBCORE_EXPORT static RefPtr<LegacyWebArchive> create(SharedBuffer&);
44
    WEBCORE_EXPORT static RefPtr<LegacyWebArchive> create(FragmentedSharedBuffer&);
45
    WEBCORE_EXPORT static RefPtr<LegacyWebArchive> create(const URL&, SharedBuffer&);
45
    WEBCORE_EXPORT static RefPtr<LegacyWebArchive> create(const URL&, FragmentedSharedBuffer&);
46
    WEBCORE_EXPORT static Ref<LegacyWebArchive> create(Ref<ArchiveResource>&& mainResource, Vector<Ref<ArchiveResource>>&& subresources, Vector<Ref<LegacyWebArchive>>&& subframeArchives);
46
    WEBCORE_EXPORT static Ref<LegacyWebArchive> create(Ref<ArchiveResource>&& mainResource, Vector<Ref<ArchiveResource>>&& subresources, Vector<Ref<LegacyWebArchive>>&& subframeArchives);
47
    WEBCORE_EXPORT static RefPtr<LegacyWebArchive> create(Node&, Function<bool(Frame&)>&& frameFilter = { });
47
    WEBCORE_EXPORT static RefPtr<LegacyWebArchive> create(Node&, Function<bool(Frame&)>&& frameFilter = { });
48
    WEBCORE_EXPORT static RefPtr<LegacyWebArchive> create(Frame&);
48
    WEBCORE_EXPORT static RefPtr<LegacyWebArchive> create(Frame&);
- a/Source/WebCore/loader/archive/mhtml/MHTMLArchive.cpp -11 / +11 lines
Lines 106-112 Ref<MHTMLArchive> MHTMLArchive::create() a/Source/WebCore/loader/archive/mhtml/MHTMLArchive.cpp_sec1
106
    return adoptRef(*new MHTMLArchive);
106
    return adoptRef(*new MHTMLArchive);
107
}
107
}
108
108
109
RefPtr<MHTMLArchive> MHTMLArchive::create(const URL& url, SharedBuffer& data)
109
RefPtr<MHTMLArchive> MHTMLArchive::create(const URL& url, FragmentedSharedBuffer& data)
110
{
110
{
111
    // For security reasons we only load MHTML pages from local URLs.
111
    // For security reasons we only load MHTML pages from local URLs.
112
    if (!LegacySchemeRegistry::shouldTreatURLSchemeAsLocal(url.protocol().toString()))
112
    if (!LegacySchemeRegistry::shouldTreatURLSchemeAsLocal(url.protocol().toString()))
Lines 130-136 RefPtr<MHTMLArchive> MHTMLArchive::create(const URL& url, SharedBuffer& data) a/Source/WebCore/loader/archive/mhtml/MHTMLArchive.cpp_sec2
130
    return mainArchive;
130
    return mainArchive;
131
}
131
}
132
132
133
Ref<SharedBuffer> MHTMLArchive::generateMHTMLData(Page* page)
133
Ref<FragmentedSharedBuffer> MHTMLArchive::generateMHTMLData(Page* page)
134
{
134
{
135
    Vector<PageSerializer::Resource> resources;
135
    Vector<PageSerializer::Resource> resources;
136
    PageSerializer pageSerializer(resources);
136
    PageSerializer pageSerializer(resources);
Lines 162-169 Ref<SharedBuffer> MHTMLArchive::generateMHTMLData(Page* page) a/Source/WebCore/loader/archive/mhtml/MHTMLArchive.cpp_sec3
162
    // We use utf8() below instead of ascii() as ascii() replaces CRLFs with ?? (we still only have put ASCII characters in it).
162
    // We use utf8() below instead of ascii() as ascii() replaces CRLFs with ?? (we still only have put ASCII characters in it).
163
    ASSERT(stringBuilder.toString().isAllASCII());
163
    ASSERT(stringBuilder.toString().isAllASCII());
164
    CString asciiString = stringBuilder.toString().utf8();
164
    CString asciiString = stringBuilder.toString().utf8();
165
    auto mhtmlData = SharedBuffer::create();
165
    SharedBufferBuilder mhtmlData;
166
    mhtmlData->append(asciiString.data(), asciiString.length());
166
    mhtmlData.append(asciiString.data(), asciiString.length());
167
167
168
    for (auto& resource : resources) {
168
    for (auto& resource : resources) {
169
        stringBuilder.clear();
169
        stringBuilder.clear();
Lines 178-192 Ref<SharedBuffer> MHTMLArchive::generateMHTMLData(Page* page) a/Source/WebCore/loader/archive/mhtml/MHTMLArchive.cpp_sec4
178
        stringBuilder.append("\r\nContent-Transfer-Encoding: ", contentEncoding, "\r\nContent-Location: ", resource.url.string(), "\r\n\r\n");
178
        stringBuilder.append("\r\nContent-Transfer-Encoding: ", contentEncoding, "\r\nContent-Location: ", resource.url.string(), "\r\n\r\n");
179
179
180
        asciiString = stringBuilder.toString().utf8();
180
        asciiString = stringBuilder.toString().utf8();
181
        mhtmlData->append(asciiString.data(), asciiString.length());
181
        mhtmlData.append(asciiString.data(), asciiString.length());
182
182
183
        // FIXME: ideally we would encode the content as a stream without having to fetch it all.
183
        // FIXME: ideally we would encode the content as a stream without having to fetch it all.
184
        auto* data = resource.data->data();
184
        auto* data = resource.data->data();
185
        size_t dataLength = resource.data->size();
185
        size_t dataLength = resource.data->size();
186
        if (!strcmp(contentEncoding, quotedPrintable)) {
186
        if (!strcmp(contentEncoding, quotedPrintable)) {
187
            auto encodedData = quotedPrintableEncode(data, dataLength);
187
            auto encodedData = quotedPrintableEncode(data, dataLength);
188
            mhtmlData->append(encodedData.data(), encodedData.size());
188
            mhtmlData.append(encodedData.data(), encodedData.size());
189
            mhtmlData->append("\r\n", 2);
189
            mhtmlData.append("\r\n", 2);
190
        } else {
190
        } else {
191
            ASSERT(!strcmp(contentEncoding, base64));
191
            ASSERT(!strcmp(contentEncoding, base64));
192
            // We are not specifying insertLFs = true below as it would cut the lines with LFs and MHTML requires CRLFs.
192
            // We are not specifying insertLFs = true below as it would cut the lines with LFs and MHTML requires CRLFs.
Lines 196-212 Ref<SharedBuffer> MHTMLArchive::generateMHTMLData(Page* page) a/Source/WebCore/loader/archive/mhtml/MHTMLArchive.cpp_sec5
196
            size_t encodedDataLength = encodedData.size();
196
            size_t encodedDataLength = encodedData.size();
197
            do {
197
            do {
198
                size_t lineLength = std::min(encodedDataLength - index, maximumLineLength);
198
                size_t lineLength = std::min(encodedDataLength - index, maximumLineLength);
199
                mhtmlData->append(encodedData.data() + index, lineLength);
199
                mhtmlData.append(encodedData.data() + index, lineLength);
200
                mhtmlData->append("\r\n", 2);
200
                mhtmlData.append("\r\n", 2);
201
                index += maximumLineLength;
201
                index += maximumLineLength;
202
            } while (index < encodedDataLength);
202
            } while (index < encodedDataLength);
203
        }
203
        }
204
    }
204
    }
205
205
206
    asciiString = makeString("--", boundary, "--\r\n").utf8();
206
    asciiString = makeString("--", boundary, "--\r\n").utf8();
207
    mhtmlData->append(asciiString.data(), asciiString.length());
207
    mhtmlData.append(asciiString.data(), asciiString.length());
208
208
209
    return mhtmlData;
209
    return mhtmlData.take();
210
}
210
}
211
211
212
}
212
}
- a/Source/WebCore/loader/archive/mhtml/MHTMLArchive.h -3 / +3 lines
Lines 38-51 namespace WebCore { a/Source/WebCore/loader/archive/mhtml/MHTMLArchive.h_sec1
38
38
39
class MHTMLParser;
39
class MHTMLParser;
40
class Page;
40
class Page;
41
class SharedBuffer;
41
class FragmentedSharedBuffer;
42
42
43
class MHTMLArchive final : public Archive {
43
class MHTMLArchive final : public Archive {
44
public:
44
public:
45
    static Ref<MHTMLArchive> create();
45
    static Ref<MHTMLArchive> create();
46
    static RefPtr<MHTMLArchive> create(const URL&, SharedBuffer&);
46
    static RefPtr<MHTMLArchive> create(const URL&, FragmentedSharedBuffer&);
47
47
48
    static Ref<SharedBuffer> generateMHTMLData(Page*);
48
    static Ref<FragmentedSharedBuffer> generateMHTMLData(Page*);
49
49
50
    virtual ~MHTMLArchive();
50
    virtual ~MHTMLArchive();
51
51
- a/Source/WebCore/loader/archive/mhtml/MHTMLParser.cpp -8 / +9 lines
Lines 51-57 static bool skipLinesUntilBoundaryFound(SharedBufferChunkReader& lineReader, con a/Source/WebCore/loader/archive/mhtml/MHTMLParser.cpp_sec1
51
    return false;
51
    return false;
52
}
52
}
53
53
54
MHTMLParser::MHTMLParser(SharedBuffer* data)
54
MHTMLParser::MHTMLParser(FragmentedSharedBuffer* data)
55
    : m_lineReader(data, "\r\n")
55
    : m_lineReader(data, "\r\n")
56
{
56
{
57
}
57
}
Lines 140-146 RefPtr<ArchiveResource> MHTMLParser::parseNextPart(const MIMEHeader& mimeHeader, a/Source/WebCore/loader/archive/mhtml/MHTMLParser.cpp_sec2
140
{
140
{
141
    ASSERT(endOfPartBoundary.isEmpty() == endOfDocumentBoundary.isEmpty());
141
    ASSERT(endOfPartBoundary.isEmpty() == endOfDocumentBoundary.isEmpty());
142
142
143
    auto content = SharedBuffer::create();
143
    SharedBufferBuilder content;
144
    const bool checkBoundary = !endOfPartBoundary.isEmpty();
144
    const bool checkBoundary = !endOfPartBoundary.isEmpty();
145
    bool endOfPartReached = false;
145
    bool endOfPartReached = false;
146
    if (mimeHeader.contentTransferEncoding() == MIMEHeader::Binary) {
146
    if (mimeHeader.contentTransferEncoding() == MIMEHeader::Binary) {
Lines 154-160 RefPtr<ArchiveResource> MHTMLParser::parseNextPart(const MIMEHeader& mimeHeader, a/Source/WebCore/loader/archive/mhtml/MHTMLParser.cpp_sec3
154
            LOG_ERROR("Binary contents requires end of part");
154
            LOG_ERROR("Binary contents requires end of part");
155
            return nullptr;
155
            return nullptr;
156
        }
156
        }
157
        content->append(WTFMove(part));
157
        content.append(WTFMove(part));
158
        m_lineReader.setSeparator("\r\n");
158
        m_lineReader.setSeparator("\r\n");
159
        Vector<uint8_t> nextChars;
159
        Vector<uint8_t> nextChars;
160
        if (m_lineReader.peek(nextChars, 2) != 2) {
160
        if (m_lineReader.peek(nextChars, 2) != 2) {
Lines 180-189 RefPtr<ArchiveResource> MHTMLParser::parseNextPart(const MIMEHeader& mimeHeader, a/Source/WebCore/loader/archive/mhtml/MHTMLParser.cpp_sec4
180
                break;
180
                break;
181
            }
181
            }
182
            // Note that we use line.utf8() and not line.ascii() as ascii turns special characters (such as tab, line-feed...) into '?'.
182
            // Note that we use line.utf8() and not line.ascii() as ascii turns special characters (such as tab, line-feed...) into '?'.
183
            content->append(line.utf8().data(), line.length());
183
            content.append(line.utf8().data(), line.length());
184
            if (mimeHeader.contentTransferEncoding() == MIMEHeader::QuotedPrintable) {
184
            if (mimeHeader.contentTransferEncoding() == MIMEHeader::QuotedPrintable) {
185
                // The line reader removes the \r\n, but we need them for the content in this case as the QuotedPrintable decoder expects CR-LF terminated lines.
185
                // The line reader removes the \r\n, but we need them for the content in this case as the QuotedPrintable decoder expects CR-LF terminated lines.
186
                content->append("\r\n", 2);
186
                content.append("\r\n", 2);
187
            }
187
            }
188
        }
188
        }
189
    }
189
    }
Lines 193-201 RefPtr<ArchiveResource> MHTMLParser::parseNextPart(const MIMEHeader& mimeHeader, a/Source/WebCore/loader/archive/mhtml/MHTMLParser.cpp_sec5
193
    }
193
    }
194
194
195
    Vector<uint8_t> data;
195
    Vector<uint8_t> data;
196
    auto contiguousContent = content.take()->makeContiguous();
196
    switch (mimeHeader.contentTransferEncoding()) {
197
    switch (mimeHeader.contentTransferEncoding()) {
197
    case MIMEHeader::Base64: {
198
    case MIMEHeader::Base64: {
198
        auto decodedData = base64Decode(content->data(), content->size());
199
        auto decodedData = base64Decode(contiguousContent->data(), contiguousContent->size());
199
        if (!decodedData) {
200
        if (!decodedData) {
200
            LOG_ERROR("Invalid base64 content for MHTML part.");
201
            LOG_ERROR("Invalid base64 content for MHTML part.");
201
            return nullptr;
202
            return nullptr;
Lines 204-214 RefPtr<ArchiveResource> MHTMLParser::parseNextPart(const MIMEHeader& mimeHeader, a/Source/WebCore/loader/archive/mhtml/MHTMLParser.cpp_sec6
204
        break;
205
        break;
205
    }
206
    }
206
    case MIMEHeader::QuotedPrintable:
207
    case MIMEHeader::QuotedPrintable:
207
        data = quotedPrintableDecode(content->data(), content->size());
208
        data = quotedPrintableDecode(contiguousContent->data(), contiguousContent->size());
208
        break;
209
        break;
209
    case MIMEHeader::SevenBit:
210
    case MIMEHeader::SevenBit:
210
    case MIMEHeader::Binary:
211
    case MIMEHeader::Binary:
211
        data.append(content->data(), content->size());
212
        data.append(contiguousContent->data(), contiguousContent->size());
212
        break;
213
        break;
213
    default:
214
    default:
214
        LOG_ERROR("Invalid encoding for MHTML part.");
215
        LOG_ERROR("Invalid encoding for MHTML part.");
- a/Source/WebCore/loader/archive/mhtml/MHTMLParser.h -2 / +2 lines
Lines 42-52 namespace WebCore { a/Source/WebCore/loader/archive/mhtml/MHTMLParser.h_sec1
42
class ArchiveResource;
42
class ArchiveResource;
43
class MHTMLArchive;
43
class MHTMLArchive;
44
class MIMEHeader;
44
class MIMEHeader;
45
class SharedBuffer;
45
class FragmentedSharedBuffer;
46
46
47
class MHTMLParser {
47
class MHTMLParser {
48
public:
48
public:
49
    explicit MHTMLParser(SharedBuffer*);
49
    explicit MHTMLParser(FragmentedSharedBuffer*);
50
50
51
    RefPtr<MHTMLArchive> parseArchive();
51
    RefPtr<MHTMLArchive> parseArchive();
52
52
- a/Source/WebCore/loader/cache/CachedApplicationManifest.cpp -5 / +9 lines
Lines 40-51 CachedApplicationManifest::CachedApplicationManifest(CachedResourceRequest&& req a/Source/WebCore/loader/cache/CachedApplicationManifest.cpp_sec1
40
{
40
{
41
}
41
}
42
42
43
void CachedApplicationManifest::finishLoading(SharedBuffer* data, const NetworkLoadMetrics& metrics)
43
void CachedApplicationManifest::finishLoading(const FragmentedSharedBuffer* data, const NetworkLoadMetrics& metrics)
44
{
44
{
45
    m_data = data;
45
    if (data) {
46
    setEncodedSize(data ? data->size() : 0);
46
        m_data = data->makeContiguous();
47
    if (data)
47
        setEncodedSize(data->size());
48
        m_text = m_decoder->decodeAndFlush(data->data(), data->size());
48
        m_text = m_decoder->decodeAndFlush(m_data->data(), data->size());
49
    } else {
50
        m_data = nullptr;
51
        setEncodedSize(0);
52
    }
49
    CachedResource::finishLoading(data, metrics);
53
    CachedResource::finishLoading(data, metrics);
50
}
54
}
51
55
- a/Source/WebCore/loader/cache/CachedApplicationManifest.h -1 / +1 lines
Lines 42-48 public: a/Source/WebCore/loader/cache/CachedApplicationManifest.h_sec1
42
    std::optional<struct ApplicationManifest> process(const URL& manifestURL, const URL& documentURL, Document* = nullptr);
42
    std::optional<struct ApplicationManifest> process(const URL& manifestURL, const URL& documentURL, Document* = nullptr);
43
43
44
private:
44
private:
45
    void finishLoading(SharedBuffer*, const NetworkLoadMetrics&) override;
45
    void finishLoading(const FragmentedSharedBuffer*, const NetworkLoadMetrics&) override;
46
    const TextResourceDecoder* textResourceDecoder() const override { return m_decoder.ptr(); }
46
    const TextResourceDecoder* textResourceDecoder() const override { return m_decoder.ptr(); }
47
    void setEncoding(const String&) override;
47
    void setEncoding(const String&) override;
48
    String encoding() const override;
48
    String encoding() const override;
- a/Source/WebCore/loader/cache/CachedCSSStyleSheet.cpp -7 / +11 lines
Lines 81-87 const String CachedCSSStyleSheet::sheetText(MIMETypeCheckHint mimeTypeCheckHint, a/Source/WebCore/loader/cache/CachedCSSStyleSheet.cpp_sec1
81
        return m_decodedSheetText;
81
        return m_decodedSheetText;
82
82
83
    // Don't cache the decoded text, regenerating is cheap and it can use quite a bit of memory
83
    // Don't cache the decoded text, regenerating is cheap and it can use quite a bit of memory
84
    return m_decoder->decodeAndFlush(m_data->data(), m_data->size());
84
    return m_decoder->decodeAndFlush(m_data->makeContiguous()->data(), m_data->size());
85
}
85
}
86
86
87
void CachedCSSStyleSheet::setBodyDataFrom(const CachedResource& resource)
87
void CachedCSSStyleSheet::setBodyDataFrom(const CachedResource& resource)
Lines 97-109 void CachedCSSStyleSheet::setBodyDataFrom(const CachedResource& resource) a/Source/WebCore/loader/cache/CachedCSSStyleSheet.cpp_sec2
97
        saveParsedStyleSheet(*sheet.m_parsedStyleSheetCache);
97
        saveParsedStyleSheet(*sheet.m_parsedStyleSheetCache);
98
}
98
}
99
99
100
void CachedCSSStyleSheet::finishLoading(SharedBuffer* data, const NetworkLoadMetrics& metrics)
100
void CachedCSSStyleSheet::finishLoading(const FragmentedSharedBuffer* data, const NetworkLoadMetrics& metrics)
101
{
101
{
102
    m_data = data;
102
    if (data) {
103
    setEncodedSize(data ? data->size() : 0);
103
        m_data = data->makeContiguous();
104
    // Decode the data to find out the encoding and keep the sheet text around during checkNotify()
104
        setEncodedSize(data->size());
105
    if (data)
105
        // Decode the data to find out the encoding and keep the sheet text around during checkNotify()
106
        m_decodedSheetText = m_decoder->decodeAndFlush(data->data(), data->size());
106
        m_decodedSheetText = m_decoder->decodeAndFlush(m_data->data(), data->size());
107
    } else {
108
        m_data = nullptr;
109
        setEncodedSize(0);
110
    }
107
    setLoading(false);
111
    setLoading(false);
108
    checkNotify(metrics);
112
    checkNotify(metrics);
109
    // Clear the decoded text as it is unlikely to be needed immediately again and is cheap to regenerate.
113
    // Clear the decoded text as it is unlikely to be needed immediately again and is cheap to regenerate.
- a/Source/WebCore/loader/cache/CachedCSSStyleSheet.h -1 / +1 lines
Lines 55-61 private: a/Source/WebCore/loader/cache/CachedCSSStyleSheet.h_sec1
55
    void setEncoding(const String&) final;
55
    void setEncoding(const String&) final;
56
    String encoding() const final;
56
    String encoding() const final;
57
    const TextResourceDecoder* textResourceDecoder() const final { return m_decoder.get(); }
57
    const TextResourceDecoder* textResourceDecoder() const final { return m_decoder.get(); }
58
    void finishLoading(SharedBuffer*, const NetworkLoadMetrics&) final;
58
    void finishLoading(const FragmentedSharedBuffer*, const NetworkLoadMetrics&) final;
59
    void destroyDecodedData() final;
59
    void destroyDecodedData() final;
60
60
61
    void setBodyDataFrom(const CachedResource&) final;
61
    void setBodyDataFrom(const CachedResource&) final;
- a/Source/WebCore/loader/cache/CachedFont.cpp -5 / +10 lines
Lines 64-73 void CachedFont::didAddClient(CachedResourceClient& client) a/Source/WebCore/loader/cache/CachedFont.cpp_sec1
64
        static_cast<CachedFontClient&>(client).fontLoaded(*this);
64
        static_cast<CachedFontClient&>(client).fontLoaded(*this);
65
}
65
}
66
66
67
void CachedFont::finishLoading(SharedBuffer* data, const NetworkLoadMetrics& metrics)
67
void CachedFont::finishLoading(const FragmentedSharedBuffer* data, const NetworkLoadMetrics& metrics)
68
{
68
{
69
    m_data = data;
69
    if (data) {
70
    setEncodedSize(m_data.get() ? m_data->size() : 0);
70
        m_data = data->makeContiguous();
71
        setEncodedSize(m_data->size());
72
    } else {
73
        m_data = nullptr;
74
        setEncodedSize(0);
75
    }
71
    setLoading(false);
76
    setLoading(false);
72
    checkNotify(metrics);
77
    checkNotify(metrics);
73
}
78
}
Lines 105-111 bool CachedFont::ensureCustomFontData(SharedBuffer* data) a/Source/WebCore/loader/cache/CachedFont.cpp_sec2
105
110
106
std::unique_ptr<FontCustomPlatformData> CachedFont::createCustomFontData(SharedBuffer& bytes, const String& itemInCollection, bool& wrapping)
111
std::unique_ptr<FontCustomPlatformData> CachedFont::createCustomFontData(SharedBuffer& bytes, const String& itemInCollection, bool& wrapping)
107
{
112
{
108
    RefPtr buffer { &bytes };
113
    RefPtr buffer = { &bytes };
109
    wrapping = !convertWOFFToSfntIfNecessary(buffer);
114
    wrapping = !convertWOFFToSfntIfNecessary(buffer);
110
    return buffer ? createFontCustomPlatformData(*buffer, itemInCollection) : nullptr;
115
    return buffer ? createFontCustomPlatformData(*buffer, itemInCollection) : nullptr;
111
}
116
}
Lines 135-141 void CachedFont::checkNotify(const NetworkLoadMetrics&) a/Source/WebCore/loader/cache/CachedFont.cpp_sec3
135
{
140
{
136
    if (isLoading())
141
    if (isLoading())
137
        return;
142
        return;
138
    
143
139
    CachedResourceClientWalker<CachedFontClient> walker(m_clients);
144
    CachedResourceClientWalker<CachedFontClient> walker(m_clients);
140
    while (CachedFontClient* client = walker.next())
145
    while (CachedFontClient* client = walker.next())
141
        client->fontLoaded(*this);
146
        client->fontLoaded(*this);
- a/Source/WebCore/loader/cache/CachedFont.h -1 / +1 lines
Lines 74-80 private: a/Source/WebCore/loader/cache/CachedFont.h_sec1
74
    NO_RETURN_DUE_TO_ASSERT void setBodyDataFrom(const CachedResource&) final { ASSERT_NOT_REACHED(); }
74
    NO_RETURN_DUE_TO_ASSERT void setBodyDataFrom(const CachedResource&) final { ASSERT_NOT_REACHED(); }
75
75
76
    void didAddClient(CachedResourceClient&) override;
76
    void didAddClient(CachedResourceClient&) override;
77
    void finishLoading(SharedBuffer*, const NetworkLoadMetrics&) override;
77
    void finishLoading(const FragmentedSharedBuffer*, const NetworkLoadMetrics&) override;
78
78
79
    void allClientsRemoved() override;
79
    void allClientsRemoved() override;
80
80
- a/Source/WebCore/loader/cache/CachedImage.cpp -9 / +11 lines
Lines 468-476 inline void CachedImage::clearImage() a/Source/WebCore/loader/cache/CachedImage.cpp_sec1
468
    m_updateImageDataCount = 0;
468
    m_updateImageDataCount = 0;
469
}
469
}
470
470
471
void CachedImage::updateBufferInternal(SharedBuffer& data)
471
void CachedImage::updateBufferInternal(const FragmentedSharedBuffer& data)
472
{
472
{
473
    m_data = &data;
473
    m_data = data.makeContiguous();
474
    setEncodedSize(m_data->size());
474
    setEncodedSize(m_data->size());
475
    createImage();
475
    createImage();
476
476
Lines 523-534 bool CachedImage::shouldDeferUpdateImageData() const a/Source/WebCore/loader/cache/CachedImage.cpp_sec2
523
    return (MonotonicTime::now() - m_lastUpdateImageDataTime).seconds() < updateImageDataBackoffIntervals[interval];
523
    return (MonotonicTime::now() - m_lastUpdateImageDataTime).seconds() < updateImageDataBackoffIntervals[interval];
524
}
524
}
525
525
526
RefPtr<SharedBuffer> CachedImage::convertedDataIfNeeded(SharedBuffer* data) const
526
RefPtr<SharedBuffer> CachedImage::convertedDataIfNeeded(const FragmentedSharedBuffer* data) const
527
{
527
{
528
    if (!data || !isPostScriptResource())
528
    if (!data)
529
        return data;
529
        return nullptr;
530
    if (!isPostScriptResource())
531
        return data->makeContiguous();
530
#if PLATFORM(MAC) && !USE(WEBKIT_IMAGE_DECODERS)
532
#if PLATFORM(MAC) && !USE(WEBKIT_IMAGE_DECODERS)
531
    return SharedBuffer::create(PDFDocumentImage::convertPostScriptDataToPDF(data->createCFData()).get());
533
    return SharedBuffer::create(PDFDocumentImage::convertPostScriptDataToPDF(data->makeContiguous()->createCFData()).get());
532
#else
534
#else
533
    // Loading the image should have been canceled if the system does not support converting PostScript to PDF.
535
    // Loading the image should have been canceled if the system does not support converting PostScript to PDF.
534
    ASSERT_NOT_REACHED();
536
    ASSERT_NOT_REACHED();
Lines 553-559 EncodedDataStatus CachedImage::updateImageData(bool allDataReceived) a/Source/WebCore/loader/cache/CachedImage.cpp_sec3
553
    return result;
555
    return result;
554
}
556
}
555
557
556
void CachedImage::updateBuffer(SharedBuffer& data)
558
void CachedImage::updateBuffer(const FragmentedSharedBuffer& data)
557
{
559
{
558
    ASSERT(dataBufferingPolicy() == DataBufferingPolicy::BufferData);
560
    ASSERT(dataBufferingPolicy() == DataBufferingPolicy::BufferData);
559
    updateBufferInternal(data);
561
    updateBufferInternal(data);
Lines 567-573 void CachedImage::updateData(const uint8_t* data, unsigned length) a/Source/WebCore/loader/cache/CachedImage.cpp_sec4
567
    CachedResource::updateData(data, length);
569
    CachedResource::updateData(data, length);
568
}
570
}
569
571
570
void CachedImage::finishLoading(SharedBuffer* data, const NetworkLoadMetrics& metrics)
572
void CachedImage::finishLoading(const FragmentedSharedBuffer* data, const NetworkLoadMetrics& metrics)
571
{
573
{
572
    m_data = convertedDataIfNeeded(data);
574
    m_data = convertedDataIfNeeded(data);
573
    if (m_data) {
575
    if (m_data) {
Lines 593-599 void CachedImage::finishLoading(SharedBuffer* data, const NetworkLoadMetrics& me a/Source/WebCore/loader/cache/CachedImage.cpp_sec5
593
void CachedImage::didReplaceSharedBufferContents()
595
void CachedImage::didReplaceSharedBufferContents()
594
{
596
{
595
    if (m_image) {
597
    if (m_image) {
596
        // Let the Image know that the SharedBuffer has been rejigged, so it can let go of any references to the heap-allocated resource buffer.
598
        // Let the Image know that the FragmentedSharedBuffer has been rejigged, so it can let go of any references to the heap-allocated resource buffer.
597
        // FIXME(rdar://problem/24275617): It would be better if we could somehow tell the Image's decoder to swap in the new contents without destroying anything.
599
        // FIXME(rdar://problem/24275617): It would be better if we could somehow tell the Image's decoder to swap in the new contents without destroying anything.
598
        m_image->destroyDecodedData(true);
600
        m_image->destroyDecodedData(true);
599
    }
601
    }
- a/Source/WebCore/loader/cache/CachedImage.h -4 / +4 lines
Lines 69-76 public: a/Source/WebCore/loader/cache/CachedImage.h_sec1
69
    bool imageHasRelativeWidth() const { return m_image && m_image->hasRelativeWidth(); }
69
    bool imageHasRelativeWidth() const { return m_image && m_image->hasRelativeWidth(); }
70
    bool imageHasRelativeHeight() const { return m_image && m_image->hasRelativeHeight(); }
70
    bool imageHasRelativeHeight() const { return m_image && m_image->hasRelativeHeight(); }
71
71
72
    void updateBuffer(SharedBuffer&) override;
72
    void updateBuffer(const FragmentedSharedBuffer&) override;
73
    void finishLoading(SharedBuffer*, const NetworkLoadMetrics&) override;
73
    void finishLoading(const FragmentedSharedBuffer*, const NetworkLoadMetrics&) override;
74
74
75
    enum SizeType {
75
    enum SizeType {
76
        UsedSize,
76
        UsedSize,
Lines 125-131 private: a/Source/WebCore/loader/cache/CachedImage.h_sec2
125
    void destroyDecodedData() override;
125
    void destroyDecodedData() override;
126
126
127
    bool shouldDeferUpdateImageData() const;
127
    bool shouldDeferUpdateImageData() const;
128
    RefPtr<SharedBuffer> convertedDataIfNeeded(SharedBuffer* data) const;
128
    RefPtr<SharedBuffer> convertedDataIfNeeded(const FragmentedSharedBuffer* data) const;
129
    void didUpdateImageData();
129
    void didUpdateImageData();
130
    EncodedDataStatus updateImageData(bool allDataReceived);
130
    EncodedDataStatus updateImageData(bool allDataReceived);
131
    void updateData(const uint8_t* data, unsigned length) override;
131
    void updateData(const uint8_t* data, unsigned length) override;
Lines 169-175 private: a/Source/WebCore/loader/cache/CachedImage.h_sec3
169
    void changedInRect(const Image&, const IntRect*);
169
    void changedInRect(const Image&, const IntRect*);
170
    void scheduleRenderingUpdate(const Image&);
170
    void scheduleRenderingUpdate(const Image&);
171
171
172
    void updateBufferInternal(SharedBuffer&);
172
    void updateBufferInternal(const FragmentedSharedBuffer&);
173
173
174
    void didReplaceSharedBufferContents() override;
174
    void didReplaceSharedBufferContents() override;
175
175
- a/Source/WebCore/loader/cache/CachedRawResource.cpp -10 / +12 lines
Lines 48-54 CachedRawResource::CachedRawResource(CachedResourceRequest&& request, Type type, a/Source/WebCore/loader/cache/CachedRawResource.cpp_sec1
48
    ASSERT(isMainOrMediaOrIconOrRawResource());
48
    ASSERT(isMainOrMediaOrIconOrRawResource());
49
}
49
}
50
50
51
std::optional<SharedBufferDataView> CachedRawResource::calculateIncrementalDataChunk(const SharedBuffer* data) const
51
std::optional<SharedBufferDataView> CachedRawResource::calculateIncrementalDataChunk(const FragmentedSharedBuffer* data) const
52
{
52
{
53
    size_t previousDataLength = encodedSize();
53
    size_t previousDataLength = encodedSize();
54
    if (!data || data->size() <= previousDataLength)
54
    if (!data || data->size() <= previousDataLength)
Lines 56-62 std::optional<SharedBufferDataView> CachedRawResource::calculateIncrementalDataC a/Source/WebCore/loader/cache/CachedRawResource.cpp_sec2
56
    return data->getSomeData(previousDataLength);
56
    return data->getSomeData(previousDataLength);
57
}
57
}
58
58
59
void CachedRawResource::updateBuffer(SharedBuffer& data)
59
void CachedRawResource::updateBuffer(const FragmentedSharedBuffer& data)
60
{
60
{
61
    // Skip any updateBuffers triggered from nested runloops. We'll have the complete buffer in finishLoading.
61
    // Skip any updateBuffers triggered from nested runloops. We'll have the complete buffer in finishLoading.
62
    if (m_inIncrementalDataNotify)
62
    if (m_inIncrementalDataNotify)
Lines 64-70 void CachedRawResource::updateBuffer(SharedBuffer& data) a/Source/WebCore/loader/cache/CachedRawResource.cpp_sec3
64
64
65
    CachedResourceHandle<CachedRawResource> protectedThis(this);
65
    CachedResourceHandle<CachedRawResource> protectedThis(this);
66
    ASSERT(dataBufferingPolicy() == DataBufferingPolicy::BufferData);
66
    ASSERT(dataBufferingPolicy() == DataBufferingPolicy::BufferData);
67
    m_data = &data;
67
    m_data = data.makeContiguous();
68
68
69
    auto previousDataSize = encodedSize();
69
    auto previousDataSize = encodedSize();
70
    while (data.size() > previousDataSize) {
70
    while (data.size() > previousDataSize) {
Lines 96-102 void CachedRawResource::updateData(const uint8_t* data, unsigned length) a/Source/WebCore/loader/cache/CachedRawResource.cpp_sec4
96
    CachedResource::updateData(data, length);
96
    CachedResource::updateData(data, length);
97
}
97
}
98
98
99
void CachedRawResource::finishLoading(SharedBuffer* data, const NetworkLoadMetrics& metrics)
99
void CachedRawResource::finishLoading(const FragmentedSharedBuffer* data, const NetworkLoadMetrics& metrics)
100
{
100
{
101
    if (m_inIncrementalDataNotify) {
101
    if (m_inIncrementalDataNotify) {
102
        // We may get here synchronously from updateBuffer() if the callback there ends up spinning a runloop.
102
        // We may get here synchronously from updateBuffer() if the callback there ends up spinning a runloop.
Lines 107-118 void CachedRawResource::finishLoading(SharedBuffer* data, const NetworkLoadMetri a/Source/WebCore/loader/cache/CachedRawResource.cpp_sec5
107
    CachedResourceHandle<CachedRawResource> protectedThis(this);
107
    CachedResourceHandle<CachedRawResource> protectedThis(this);
108
    DataBufferingPolicy dataBufferingPolicy = this->dataBufferingPolicy();
108
    DataBufferingPolicy dataBufferingPolicy = this->dataBufferingPolicy();
109
    if (dataBufferingPolicy == DataBufferingPolicy::BufferData) {
109
    if (dataBufferingPolicy == DataBufferingPolicy::BufferData) {
110
        m_data = data;
110
        if (data) {
111
111
            m_data = data->makeContiguous();
112
        if (auto incrementalData = calculateIncrementalDataChunk(data)) {
112
            if (auto incrementalData = calculateIncrementalDataChunk(data)) {
113
            setEncodedSize(data->size());
113
                setEncodedSize(data->size());
114
            notifyClientsDataWasReceived(incrementalData->data(), incrementalData->size());
114
                notifyClientsDataWasReceived(incrementalData->data(), incrementalData->size());
115
        }
115
            }
116
        } else
117
            m_data = nullptr;
116
    }
118
    }
117
119
118
#if USE(QUICK_LOOK)
120
#if USE(QUICK_LOOK)
- a/Source/WebCore/loader/cache/CachedRawResource.h -4 / +4 lines
Lines 51-59 public: a/Source/WebCore/loader/cache/CachedRawResource.h_sec1
51
51
52
private:
52
private:
53
    void didAddClient(CachedResourceClient&) final;
53
    void didAddClient(CachedResourceClient&) final;
54
    void updateBuffer(SharedBuffer&) final;
54
    void updateBuffer(const FragmentedSharedBuffer&) final;
55
    void updateData(const uint8_t* data, unsigned length) final;
55
    void updateData(const uint8_t* data, unsigned length) final;
56
    void finishLoading(SharedBuffer*, const NetworkLoadMetrics&) final;
56
    void finishLoading(const FragmentedSharedBuffer*, const NetworkLoadMetrics&) final;
57
57
58
    bool shouldIgnoreHTTPStatusCodeErrors() const override { return true; }
58
    bool shouldIgnoreHTTPStatusCodeErrors() const override { return true; }
59
    void allClientsRemoved() override;
59
    void allClientsRemoved() override;
Lines 66-72 private: a/Source/WebCore/loader/cache/CachedRawResource.h_sec2
66
    void switchClientsToRevalidatedResource() override;
66
    void switchClientsToRevalidatedResource() override;
67
    bool mayTryReplaceEncodedData() const override { return m_allowEncodedDataReplacement; }
67
    bool mayTryReplaceEncodedData() const override { return m_allowEncodedDataReplacement; }
68
68
69
    std::optional<SharedBufferDataView> calculateIncrementalDataChunk(const SharedBuffer*) const;
69
    std::optional<SharedBufferDataView> calculateIncrementalDataChunk(const FragmentedSharedBuffer*) const;
70
    void notifyClientsDataWasReceived(const uint8_t* data, unsigned length);
70
    void notifyClientsDataWasReceived(const uint8_t* data, unsigned length);
71
    
71
    
72
#if USE(QUICK_LOOK)
72
#if USE(QUICK_LOOK)
Lines 92-98 private: a/Source/WebCore/loader/cache/CachedRawResource.h_sec3
92
    Vector<RedirectPair, 0, CrashOnOverflow, 0> m_redirectChain;
92
    Vector<RedirectPair, 0, CrashOnOverflow, 0> m_redirectChain;
93
93
94
    struct DelayedFinishLoading {
94
    struct DelayedFinishLoading {
95
        RefPtr<SharedBuffer> buffer;
95
        RefPtr<const FragmentedSharedBuffer> buffer;
96
    };
96
    };
97
    std::optional<DelayedFinishLoading> m_delayedFinishLoading;
97
    std::optional<DelayedFinishLoading> m_delayedFinishLoading;
98
};
98
};
- a/Source/WebCore/loader/cache/CachedResource.cpp -4 / +3 lines
Lines 334-340 void CachedResource::checkNotify(const NetworkLoadMetrics& metrics) a/Source/WebCore/loader/cache/CachedResource.cpp_sec1
334
        client->notifyFinished(*this, metrics);
334
        client->notifyFinished(*this, metrics);
335
}
335
}
336
336
337
void CachedResource::updateBuffer(SharedBuffer&)
337
void CachedResource::updateBuffer(const FragmentedSharedBuffer&)
338
{
338
{
339
    ASSERT(dataBufferingPolicy() == DataBufferingPolicy::BufferData);
339
    ASSERT(dataBufferingPolicy() == DataBufferingPolicy::BufferData);
340
}
340
}
Lines 344-350 void CachedResource::updateData(const uint8_t*, unsigned) a/Source/WebCore/loader/cache/CachedResource.cpp_sec2
344
    ASSERT(dataBufferingPolicy() == DataBufferingPolicy::DoNotBufferData);
344
    ASSERT(dataBufferingPolicy() == DataBufferingPolicy::DoNotBufferData);
345
}
345
}
346
346
347
void CachedResource::finishLoading(SharedBuffer*, const NetworkLoadMetrics& metrics)
347
void CachedResource::finishLoading(const FragmentedSharedBuffer*, const NetworkLoadMetrics& metrics)
348
{
348
{
349
    setLoading(false);
349
    setLoading(false);
350
    checkNotify(metrics);
350
    checkNotify(metrics);
Lines 927-934 void CachedResource::tryReplaceEncodedData(SharedBuffer& newBuffer) a/Source/WebCore/loader/cache/CachedResource.cpp_sec3
927
    if (*m_data != newBuffer)
927
    if (*m_data != newBuffer)
928
        return;
928
        return;
929
929
930
    m_data->clear();
930
    m_data = Ref { newBuffer };
931
    m_data->append(newBuffer);
932
    didReplaceSharedBufferContents();
931
    didReplaceSharedBufferContents();
933
}
932
}
934
933
- a/Source/WebCore/loader/cache/CachedResource.h -3 / +3 lines
Lines 49-55 class CookieJar; a/Source/WebCore/loader/cache/CachedResource.h_sec1
49
class MemoryCache;
49
class MemoryCache;
50
class NetworkLoadMetrics;
50
class NetworkLoadMetrics;
51
class SecurityOrigin;
51
class SecurityOrigin;
52
class SharedBuffer;
52
class FragmentedSharedBuffer;
53
class SubresourceLoader;
53
class SubresourceLoader;
54
class TextResourceDecoder;
54
class TextResourceDecoder;
55
55
Lines 112-120 public: a/Source/WebCore/loader/cache/CachedResource.h_sec2
112
    virtual void setEncoding(const String&) { }
112
    virtual void setEncoding(const String&) { }
113
    virtual String encoding() const { return String(); }
113
    virtual String encoding() const { return String(); }
114
    virtual const TextResourceDecoder* textResourceDecoder() const { return nullptr; }
114
    virtual const TextResourceDecoder* textResourceDecoder() const { return nullptr; }
115
    virtual void updateBuffer(SharedBuffer&);
115
    virtual void updateBuffer(const FragmentedSharedBuffer&);
116
    virtual void updateData(const uint8_t* data, unsigned length);
116
    virtual void updateData(const uint8_t* data, unsigned length);
117
    virtual void finishLoading(SharedBuffer*, const NetworkLoadMetrics&);
117
    virtual void finishLoading(const FragmentedSharedBuffer*, const NetworkLoadMetrics&);
118
    virtual void error(CachedResource::Status);
118
    virtual void error(CachedResource::Status);
119
119
120
    void setResourceError(const ResourceError& error) { m_error = error; }
120
    void setResourceError(const ResourceError& error) { m_error = error; }
- a/Source/WebCore/loader/cache/CachedSVGDocument.cpp -2 / +2 lines
Lines 52-63 String CachedSVGDocument::encoding() const a/Source/WebCore/loader/cache/CachedSVGDocument.cpp_sec1
52
    return m_decoder->encoding().name();
52
    return m_decoder->encoding().name();
53
}
53
}
54
54
55
void CachedSVGDocument::finishLoading(SharedBuffer* data, const NetworkLoadMetrics& metrics)
55
void CachedSVGDocument::finishLoading(const FragmentedSharedBuffer* data, const NetworkLoadMetrics& metrics)
56
{
56
{
57
    if (data) {
57
    if (data) {
58
        // We don't need to create a new frame because the new document belongs to the parent UseElement.
58
        // We don't need to create a new frame because the new document belongs to the parent UseElement.
59
        m_document = SVGDocument::create(nullptr, m_settings, response().url());
59
        m_document = SVGDocument::create(nullptr, m_settings, response().url());
60
        m_document->setContent(m_decoder->decodeAndFlush(data->data(), data->size()));
60
        m_document->setContent(m_decoder->decodeAndFlush(data->makeContiguous()->data(), data->size()));
61
    }
61
    }
62
    CachedResource::finishLoading(data, metrics);
62
    CachedResource::finishLoading(data, metrics);
63
}
63
}
- a/Source/WebCore/loader/cache/CachedSVGDocument.h -1 / +1 lines
Lines 43-49 private: a/Source/WebCore/loader/cache/CachedSVGDocument.h_sec1
43
    void setEncoding(const String&) override;
43
    void setEncoding(const String&) override;
44
    String encoding() const override;
44
    String encoding() const override;
45
    const TextResourceDecoder* textResourceDecoder() const override { return m_decoder.get(); }
45
    const TextResourceDecoder* textResourceDecoder() const override { return m_decoder.get(); }
46
    void finishLoading(SharedBuffer*, const NetworkLoadMetrics&) override;
46
    void finishLoading(const FragmentedSharedBuffer*, const NetworkLoadMetrics&) override;
47
47
48
    RefPtr<SVGDocument> m_document;
48
    RefPtr<SVGDocument> m_document;
49
    RefPtr<TextResourceDecoder> m_decoder;
49
    RefPtr<TextResourceDecoder> m_decoder;
- a/Source/WebCore/loader/cache/CachedSVGFont.cpp -1 / +1 lines
Lines 80-86 bool CachedSVGFont::ensureCustomFontData(const AtomString& remoteURI) a/Source/WebCore/loader/cache/CachedSVGFont.cpp_sec1
80
80
81
            ScriptDisallowedScope::DisableAssertionsInScope disabledScope;
81
            ScriptDisallowedScope::DisableAssertionsInScope disabledScope;
82
82
83
            m_externalSVGDocument->setContent(decoder->decodeAndFlush(m_data->data(), m_data->size()));
83
            m_externalSVGDocument->setContent(decoder->decodeAndFlush(m_data->makeContiguous()->data(), m_data->size()));
84
            sawError = decoder->sawError();
84
            sawError = decoder->sawError();
85
        }
85
        }
86
86
- a/Source/WebCore/loader/cache/CachedScript.cpp -3 / +8 lines
Lines 96-105 unsigned CachedScript::scriptHash() a/Source/WebCore/loader/cache/CachedScript.cpp_sec1
96
    return m_scriptHash;
96
    return m_scriptHash;
97
}
97
}
98
98
99
void CachedScript::finishLoading(SharedBuffer* data, const NetworkLoadMetrics& metrics)
99
void CachedScript::finishLoading(const FragmentedSharedBuffer* data, const NetworkLoadMetrics& metrics)
100
{
100
{
101
    m_data = data;
101
    if (data) {
102
    setEncodedSize(data ? data->size() : 0);
102
        m_data = data->makeContiguous();
103
        setEncodedSize(data->size());
104
    } else {
105
        m_data = nullptr;
106
        setEncodedSize(0);
107
    }
103
    CachedResource::finishLoading(data, metrics);
108
    CachedResource::finishLoading(data, metrics);
104
}
109
}
105
110
- a/Source/WebCore/loader/cache/CachedScript.h -1 / +1 lines
Lines 47-53 private: a/Source/WebCore/loader/cache/CachedScript.h_sec1
47
    void setEncoding(const String&) final;
47
    void setEncoding(const String&) final;
48
    String encoding() const final;
48
    String encoding() const final;
49
    const TextResourceDecoder* textResourceDecoder() const final { return m_decoder.get(); }
49
    const TextResourceDecoder* textResourceDecoder() const final { return m_decoder.get(); }
50
    void finishLoading(SharedBuffer*, const NetworkLoadMetrics&) final;
50
    void finishLoading(const FragmentedSharedBuffer*, const NetworkLoadMetrics&) final;
51
51
52
    void destroyDecodedData() final;
52
    void destroyDecodedData() final;
53
53
- a/Source/WebCore/loader/cache/CachedTextTrack.cpp -4 / +4 lines
Lines 40-49 CachedTextTrack::CachedTextTrack(CachedResourceRequest&& request, PAL::SessionID a/Source/WebCore/loader/cache/CachedTextTrack.cpp_sec1
40
{
40
{
41
}
41
}
42
42
43
void CachedTextTrack::doUpdateBuffer(SharedBuffer* data)
43
void CachedTextTrack::doUpdateBuffer(const FragmentedSharedBuffer* data)
44
{
44
{
45
    ASSERT(dataBufferingPolicy() == DataBufferingPolicy::BufferData);
45
    ASSERT(dataBufferingPolicy() == DataBufferingPolicy::BufferData);
46
    m_data = data;
46
    m_data = data ? data->makeContiguous() : RefPtr<SharedBuffer>();
47
    setEncodedSize(data ? data->size() : 0);
47
    setEncodedSize(data ? data->size() : 0);
48
48
49
    CachedResourceClientWalker<CachedResourceClient> walker(m_clients);
49
    CachedResourceClientWalker<CachedResourceClient> walker(m_clients);
Lines 51-63 void CachedTextTrack::doUpdateBuffer(SharedBuffer* data) a/Source/WebCore/loader/cache/CachedTextTrack.cpp_sec2
51
        client->deprecatedDidReceiveCachedResource(*this);
51
        client->deprecatedDidReceiveCachedResource(*this);
52
}
52
}
53
53
54
void CachedTextTrack::updateBuffer(SharedBuffer& data)
54
void CachedTextTrack::updateBuffer(const FragmentedSharedBuffer& data)
55
{
55
{
56
    doUpdateBuffer(&data);
56
    doUpdateBuffer(&data);
57
    CachedResource::updateBuffer(data);
57
    CachedResource::updateBuffer(data);
58
}
58
}
59
59
60
void CachedTextTrack::finishLoading(SharedBuffer* data, const NetworkLoadMetrics& metrics)
60
void CachedTextTrack::finishLoading(const FragmentedSharedBuffer* data, const NetworkLoadMetrics& metrics)
61
{
61
{
62
    doUpdateBuffer(data);
62
    doUpdateBuffer(data);
63
    CachedResource::finishLoading(data, metrics);
63
    CachedResource::finishLoading(data, metrics);
- a/Source/WebCore/loader/cache/CachedTextTrack.h -3 / +3 lines
Lines 35-44 public: a/Source/WebCore/loader/cache/CachedTextTrack.h_sec1
35
35
36
private:
36
private:
37
    bool mayTryReplaceEncodedData() const override { return true; }
37
    bool mayTryReplaceEncodedData() const override { return true; }
38
    void updateBuffer(SharedBuffer&) override;
38
    void updateBuffer(const FragmentedSharedBuffer&) override;
39
    void finishLoading(SharedBuffer*, const NetworkLoadMetrics&) override;
39
    void finishLoading(const FragmentedSharedBuffer*, const NetworkLoadMetrics&) override;
40
40
41
    void doUpdateBuffer(SharedBuffer*);
41
    void doUpdateBuffer(const FragmentedSharedBuffer*);
42
};
42
};
43
43
44
} // namespace WebCore
44
} // namespace WebCore
- a/Source/WebCore/loader/cache/CachedXSLStyleSheet.cpp -5 / +9 lines
Lines 61-72 String CachedXSLStyleSheet::encoding() const a/Source/WebCore/loader/cache/CachedXSLStyleSheet.cpp_sec1
61
    return m_decoder->encoding().name();
61
    return m_decoder->encoding().name();
62
}
62
}
63
63
64
void CachedXSLStyleSheet::finishLoading(SharedBuffer* data, const NetworkLoadMetrics& metrics)
64
void CachedXSLStyleSheet::finishLoading(const FragmentedSharedBuffer* data, const NetworkLoadMetrics& metrics)
65
{
65
{
66
    m_data = data;
66
    if (data) {
67
    setEncodedSize(data ? data->size() : 0);
67
        m_data = data->makeContiguous();
68
    if (data)
68
        setEncodedSize(data->size());
69
        m_sheet = m_decoder->decodeAndFlush(data->data(), encodedSize());
69
        m_sheet = m_decoder->decodeAndFlush(m_data->data(), encodedSize());
70
    } else {
71
        m_data = nullptr;
72
        setEncodedSize(0);
73
    }
70
    setLoading(false);
74
    setLoading(false);
71
    checkNotify(metrics);
75
    checkNotify(metrics);
72
}
76
}
- a/Source/WebCore/loader/cache/CachedXSLStyleSheet.h -1 / +1 lines
Lines 47-53 private: a/Source/WebCore/loader/cache/CachedXSLStyleSheet.h_sec1
47
    void setEncoding(const String&) final;
47
    void setEncoding(const String&) final;
48
    String encoding() const final;
48
    String encoding() const final;
49
    const TextResourceDecoder* textResourceDecoder() const final { return m_decoder.get(); }
49
    const TextResourceDecoder* textResourceDecoder() const final { return m_decoder.get(); }
50
    void finishLoading(SharedBuffer*, const NetworkLoadMetrics&) final;
50
    void finishLoading(const FragmentedSharedBuffer*, const NetworkLoadMetrics&) final;
51
51
52
    String m_sheet;
52
    String m_sheet;
53
    RefPtr<TextResourceDecoder> m_decoder;
53
    RefPtr<TextResourceDecoder> m_decoder;
- a/Source/WebCore/loader/ios/LegacyPreviewLoader.h -5 / +7 lines
Lines 30-35 a/Source/WebCore/loader/ios/LegacyPreviewLoader.h_sec1
30
#include <wtf/Forward.h>
30
#include <wtf/Forward.h>
31
#include <wtf/Noncopyable.h>
31
#include <wtf/Noncopyable.h>
32
#include <wtf/RetainPtr.h>
32
#include <wtf/RetainPtr.h>
33
#include <wtf/UniqueRef.h>
33
#include <wtf/WeakPtr.h>
34
#include <wtf/WeakPtr.h>
34
35
35
namespace WebCore {
36
namespace WebCore {
Lines 37-43 namespace WebCore { a/Source/WebCore/loader/ios/LegacyPreviewLoader.h_sec2
37
class LegacyPreviewLoaderClient;
38
class LegacyPreviewLoaderClient;
38
class ResourceLoader;
39
class ResourceLoader;
39
class ResourceResponse;
40
class ResourceResponse;
40
class SharedBuffer;
41
class FragmentedSharedBuffer;
42
class SharedBufferBuilder;
41
43
42
class LegacyPreviewLoader final : private PreviewConverterClient, private PreviewConverterProvider {
44
class LegacyPreviewLoader final : private PreviewConverterClient, private PreviewConverterProvider {
43
    WTF_MAKE_FAST_ALLOCATED;
45
    WTF_MAKE_FAST_ALLOCATED;
Lines 48-54 public: a/Source/WebCore/loader/ios/LegacyPreviewLoader.h_sec3
48
50
49
    bool didReceiveResponse(const ResourceResponse&);
51
    bool didReceiveResponse(const ResourceResponse&);
50
    bool didReceiveData(const uint8_t* data, unsigned length);
52
    bool didReceiveData(const uint8_t* data, unsigned length);
51
    bool didReceiveBuffer(const SharedBuffer&);
53
    bool didReceiveBuffer(const FragmentedSharedBuffer&);
52
    bool didFinishLoading();
54
    bool didFinishLoading();
53
    void didFail();
55
    void didFail();
54
56
Lines 60-76 private: a/Source/WebCore/loader/ios/LegacyPreviewLoader.h_sec4
60
    void previewConverterDidFinishUpdating(PreviewConverter&) final { };
62
    void previewConverterDidFinishUpdating(PreviewConverter&) final { };
61
    void previewConverterDidFailUpdating(PreviewConverter&) final;
63
    void previewConverterDidFailUpdating(PreviewConverter&) final;
62
    void previewConverterDidStartConverting(PreviewConverter&) final;
64
    void previewConverterDidStartConverting(PreviewConverter&) final;
63
    void previewConverterDidReceiveData(PreviewConverter&, const SharedBuffer&) final;
65
    void previewConverterDidReceiveData(PreviewConverter&, const FragmentedSharedBuffer&) final;
64
    void previewConverterDidFinishConverting(PreviewConverter&) final;
66
    void previewConverterDidFinishConverting(PreviewConverter&) final;
65
    void previewConverterDidFailConverting(PreviewConverter&) final;
67
    void previewConverterDidFailConverting(PreviewConverter&) final;
66
68
67
    // PreviewConverterProvider
69
    // PreviewConverterProvider
68
    void provideMainResourceForPreviewConverter(PreviewConverter&, CompletionHandler<void(const SharedBuffer*)>&&) final;
70
    void provideMainResourceForPreviewConverter(PreviewConverter&, CompletionHandler<void(Ref<FragmentedSharedBuffer>&&)>&&) final;
69
    void providePasswordForPreviewConverter(PreviewConverter&, CompletionHandler<void(const String&)>&&) final;
71
    void providePasswordForPreviewConverter(PreviewConverter&, CompletionHandler<void(const String&)>&&) final;
70
72
71
    RefPtr<PreviewConverter> m_converter;
73
    RefPtr<PreviewConverter> m_converter;
72
    Ref<LegacyPreviewLoaderClient> m_client;
74
    Ref<LegacyPreviewLoaderClient> m_client;
73
    Ref<SharedBuffer> m_originalData;
75
    UniqueRef<SharedBufferBuilder> m_originalData;
74
    WeakPtr<ResourceLoader> m_resourceLoader;
76
    WeakPtr<ResourceLoader> m_resourceLoader;
75
    bool m_finishedLoadingDataIntoConverter { false };
77
    bool m_finishedLoadingDataIntoConverter { false };
76
    bool m_hasProcessedResponse { false };
78
    bool m_hasProcessedResponse { false };
- a/Source/WebCore/loader/ios/LegacyPreviewLoader.mm -6 / +6 lines
Lines 63-69 static Ref<LegacyPreviewLoaderClient> makeClient(const ResourceLoader& loader, c a/Source/WebCore/loader/ios/LegacyPreviewLoader.mm_sec1
63
    return emptyClient();
63
    return emptyClient();
64
}
64
}
65
65
66
bool LegacyPreviewLoader::didReceiveBuffer(const SharedBuffer& buffer)
66
bool LegacyPreviewLoader::didReceiveBuffer(const FragmentedSharedBuffer& buffer)
67
{
67
{
68
    if (m_finishedLoadingDataIntoConverter)
68
    if (m_finishedLoadingDataIntoConverter)
69
        return false;
69
        return false;
Lines 109-115 void LegacyPreviewLoader::previewConverterDidStartConverting(PreviewConverter& c a/Source/WebCore/loader/ios/LegacyPreviewLoader.mm_sec2
109
        return;
109
        return;
110
110
111
    ASSERT(!m_hasProcessedResponse);
111
    ASSERT(!m_hasProcessedResponse);
112
    m_originalData->clear();
112
    m_originalData->reset();
113
    resourceLoader->documentLoader()->setPreviewConverter(WTFMove(m_converter));
113
    resourceLoader->documentLoader()->setPreviewConverter(WTFMove(m_converter));
114
    auto response { converter.previewResponse() };
114
    auto response { converter.previewResponse() };
115
115
Lines 147-153 void LegacyPreviewLoader::previewConverterDidStartConverting(PreviewConverter& c a/Source/WebCore/loader/ios/LegacyPreviewLoader.mm_sec3
147
    });
147
    });
148
}
148
}
149
149
150
void LegacyPreviewLoader::previewConverterDidReceiveData(PreviewConverter&, const SharedBuffer& data)
150
void LegacyPreviewLoader::previewConverterDidReceiveData(PreviewConverter&, const FragmentedSharedBuffer& data)
151
{
151
{
152
    auto resourceLoader = m_resourceLoader.get();
152
    auto resourceLoader = m_resourceLoader.get();
153
    if (!resourceLoader)
153
    if (!resourceLoader)
Lines 224-233 void LegacyPreviewLoader::providePasswordForPreviewConverter(PreviewConverter& c a/Source/WebCore/loader/ios/LegacyPreviewLoader.mm_sec4
224
    m_client->didRequestPassword(WTFMove(completionHandler));
224
    m_client->didRequestPassword(WTFMove(completionHandler));
225
}
225
}
226
226
227
void LegacyPreviewLoader::provideMainResourceForPreviewConverter(PreviewConverter& converter, CompletionHandler<void(const SharedBuffer*)>&& completionHandler)
227
void LegacyPreviewLoader::provideMainResourceForPreviewConverter(PreviewConverter& converter, CompletionHandler<void(Ref<FragmentedSharedBuffer>&&)>&& completionHandler)
228
{
228
{
229
    ASSERT_UNUSED(converter, &converter == m_converter);
229
    ASSERT_UNUSED(converter, &converter == m_converter);
230
    completionHandler(m_originalData.ptr());
230
    completionHandler(m_originalData->take());
231
}
231
}
232
232
233
LegacyPreviewLoader::~LegacyPreviewLoader() = default;
233
LegacyPreviewLoader::~LegacyPreviewLoader() = default;
Lines 235-241 LegacyPreviewLoader::~LegacyPreviewLoader() = default; a/Source/WebCore/loader/ios/LegacyPreviewLoader.mm_sec5
235
LegacyPreviewLoader::LegacyPreviewLoader(ResourceLoader& loader, const ResourceResponse& response)
235
LegacyPreviewLoader::LegacyPreviewLoader(ResourceLoader& loader, const ResourceResponse& response)
236
    : m_converter { PreviewConverter::create(response, *this) }
236
    : m_converter { PreviewConverter::create(response, *this) }
237
    , m_client { makeClient(loader, m_converter->previewFileName(), m_converter->previewUTI()) }
237
    , m_client { makeClient(loader, m_converter->previewFileName(), m_converter->previewUTI()) }
238
    , m_originalData { SharedBuffer::create() }
238
    , m_originalData { makeUniqueRef<SharedBufferBuilder>() }
239
    , m_resourceLoader { loader }
239
    , m_resourceLoader { loader }
240
    , m_shouldDecidePolicyBeforeLoading { loader.frame()->settings().shouldDecidePolicyBeforeLoadingQuickLookPreview() }
240
    , m_shouldDecidePolicyBeforeLoading { loader.frame()->settings().shouldDecidePolicyBeforeLoadingQuickLookPreview() }
241
{
241
{
- a/Source/WebCore/page/EditorClient.h -2 / +3 lines
Lines 38-49 namespace WebCore { a/Source/WebCore/page/EditorClient.h_sec1
38
38
39
enum class DOMPasteAccessResponse : uint8_t;
39
enum class DOMPasteAccessResponse : uint8_t;
40
40
41
class SharedBuffer;
41
class DocumentFragment;
42
class DocumentFragment;
42
class Element;
43
class Element;
43
class Frame;
44
class Frame;
44
class KeyboardEvent;
45
class KeyboardEvent;
45
class Node;
46
class Node;
46
class SharedBuffer;
47
class FragmentedSharedBuffer;
47
class StyleProperties;
48
class StyleProperties;
48
class TextCheckerClient;
49
class TextCheckerClient;
49
class VisibleSelection;
50
class VisibleSelection;
Lines 78-84 public: a/Source/WebCore/page/EditorClient.h_sec2
78
    virtual bool shouldMoveRangeAfterDelete(const SimpleRange&, const SimpleRange&) = 0;
79
    virtual bool shouldMoveRangeAfterDelete(const SimpleRange&, const SimpleRange&) = 0;
79
80
80
#if ENABLE(ATTACHMENT_ELEMENT)
81
#if ENABLE(ATTACHMENT_ELEMENT)
81
    virtual void registerAttachmentIdentifier(const String& /* identifier */, const String& /* contentType */, const String& /* preferredFileName */, Ref<SharedBuffer>&&) { }
82
    virtual void registerAttachmentIdentifier(const String& /* identifier */, const String& /* contentType */, const String& /* preferredFileName */, Ref<FragmentedSharedBuffer>&&) { }
82
    virtual void registerAttachmentIdentifier(const String& /* identifier */, const String& /* contentType */, const String& /* filePath */) { }
83
    virtual void registerAttachmentIdentifier(const String& /* identifier */, const String& /* contentType */, const String& /* filePath */) { }
83
    virtual void registerAttachments(Vector<SerializedAttachmentData>&&) { }
84
    virtual void registerAttachments(Vector<SerializedAttachmentData>&&) { }
84
    virtual void registerAttachmentIdentifier(const String& /* identifier */) { }
85
    virtual void registerAttachmentIdentifier(const String& /* identifier */) { }
- a/Source/WebCore/page/PageSerializer.cpp -2 / +2 lines
Lines 273-279 void PageSerializer::addImageToResources(CachedImage* image, RenderElement* imag a/Source/WebCore/page/PageSerializer.cpp_sec1
273
    if (!image || image->image() == &Image::nullImage())
273
    if (!image || image->image() == &Image::nullImage())
274
        return;
274
        return;
275
275
276
    RefPtr<SharedBuffer> data = imageRenderer ? image->imageForRenderer(imageRenderer)->data() : 0;
276
    RefPtr<FragmentedSharedBuffer> data = imageRenderer ? image->imageForRenderer(imageRenderer)->data() : 0;
277
    if (!data)
277
    if (!data)
278
        data = image->image()->data();
278
        data = image->image()->data();
279
279
Lines 282-288 void PageSerializer::addImageToResources(CachedImage* image, RenderElement* imag a/Source/WebCore/page/PageSerializer.cpp_sec2
282
        return;
282
        return;
283
    }
283
    }
284
284
285
    m_resources.append({ url, image->response().mimeType(), WTFMove(data) });
285
    m_resources.append({ url, image->response().mimeType(), data->makeContiguous() });
286
    m_resourceURLs.add(url);
286
    m_resourceURLs.add(url);
287
}
287
}
288
288
- a/Source/WebCore/page/ShareDataReader.cpp -4 / +4 lines
Lines 35-41 namespace WebCore { a/Source/WebCore/page/ShareDataReader.cpp_sec1
35
ShareDataReader::ShareDataReader(CompletionHandler<void(ExceptionOr<ShareDataWithParsedURL&>)>&& completionHandler)
35
ShareDataReader::ShareDataReader(CompletionHandler<void(ExceptionOr<ShareDataWithParsedURL&>)>&& completionHandler)
36
    : m_completionHandler(WTFMove(completionHandler))
36
    : m_completionHandler(WTFMove(completionHandler))
37
{
37
{
38
    
38
39
}
39
}
40
40
41
ShareDataReader::~ShareDataReader()
41
ShareDataReader::~ShareDataReader()
Lines 71-85 void ShareDataReader::didFinishLoading(int loadIndex, const String& fileName) a/Source/WebCore/page/ShareDataReader.cpp_sec2
71
        cancel();
71
        cancel();
72
        return;
72
        return;
73
    }
73
    }
74
    
74
75
    auto arrayBuffer = m_pendingFileLoads[loadIndex]->arrayBufferResult();
75
    auto arrayBuffer = m_pendingFileLoads[loadIndex]->arrayBufferResult();
76
    
76
77
    RawFile file;
77
    RawFile file;
78
    file.fileName = fileName;
78
    file.fileName = fileName;
79
    file.fileData = SharedBuffer::create(static_cast<const unsigned char*>(arrayBuffer->data()), arrayBuffer->byteLength());
79
    file.fileData = SharedBuffer::create(static_cast<const unsigned char*>(arrayBuffer->data()), arrayBuffer->byteLength());
80
    m_shareData.files.append(WTFMove(file));
80
    m_shareData.files.append(WTFMove(file));
81
    m_filesReadSoFar++;
81
    m_filesReadSoFar++;
82
    
82
83
    if (m_filesReadSoFar == static_cast<int>(m_pendingFileLoads.size())) {
83
    if (m_filesReadSoFar == static_cast<int>(m_pendingFileLoads.size())) {
84
        m_pendingFileLoads.clear();
84
        m_pendingFileLoads.clear();
85
        if (auto completionHandler = std::exchange(m_completionHandler, { }))
85
        if (auto completionHandler = std::exchange(m_completionHandler, { }))
- a/Source/WebCore/platform/NowPlayingManager.h -1 / +1 lines
Lines 70-76 private: a/Source/WebCore/platform/NowPlayingManager.h_sec1
70
    std::optional<NowPlayingInfo> m_nowPlayingInfo;
70
    std::optional<NowPlayingInfo> m_nowPlayingInfo;
71
    struct ArtworkCache {
71
    struct ArtworkCache {
72
        String src;
72
        String src;
73
        RefPtr<SharedBuffer> imageData;
73
        RefPtr<FragmentedSharedBuffer> imageData;
74
    };
74
    };
75
    std::optional<ArtworkCache> m_nowPlayingInfoArtwork;
75
    std::optional<ArtworkCache> m_nowPlayingInfoArtwork;
76
    bool m_setAsNowPlayingApplication { false };
76
    bool m_setAsNowPlayingApplication { false };
- a/Source/WebCore/platform/Pasteboard.cpp -1 / +1 lines
Lines 89-95 String Pasteboard::readString(size_t index, const String& type) a/Source/WebCore/platform/Pasteboard.cpp_sec1
89
    return { };
89
    return { };
90
}
90
}
91
91
92
RefPtr<WebCore::SharedBuffer> Pasteboard::readBuffer(size_t index, const String& type)
92
RefPtr<WebCore::FragmentedSharedBuffer> Pasteboard::readBuffer(size_t index, const String& type)
93
{
93
{
94
    if (auto* strategy = platformStrategies()->pasteboardStrategy())
94
    if (auto* strategy = platformStrategies()->pasteboardStrategy())
95
        return strategy->readBufferFromPasteboard(index, type, name(), context());
95
        return strategy->readBufferFromPasteboard(index, type, name(), context());
- a/Source/WebCore/platform/Pasteboard.h -8 / +9 lines
Lines 61-72 typedef struct HWND__* HWND; a/Source/WebCore/platform/Pasteboard.h_sec1
61
61
62
namespace WebCore {
62
namespace WebCore {
63
63
64
class SharedBuffer;
64
class DocumentFragment;
65
class DocumentFragment;
65
class DragData;
66
class DragData;
66
class Element;
67
class Element;
67
class Frame;
68
class Frame;
68
class PasteboardStrategy;
69
class PasteboardStrategy;
69
class SharedBuffer;
70
class FragmentedSharedBuffer;
70
71
71
struct SimpleRange;
72
struct SimpleRange;
72
73
Lines 147-162 public: a/Source/WebCore/platform/Pasteboard.h_sec2
147
    virtual bool readFilePath(const String&, PresentationSize preferredPresentationSize = { }, const String& contentType = { }) = 0;
148
    virtual bool readFilePath(const String&, PresentationSize preferredPresentationSize = { }, const String& contentType = { }) = 0;
148
    virtual bool readFilePaths(const Vector<String>&) = 0;
149
    virtual bool readFilePaths(const Vector<String>&) = 0;
149
    virtual bool readHTML(const String&) = 0;
150
    virtual bool readHTML(const String&) = 0;
150
    virtual bool readImage(Ref<SharedBuffer>&&, const String& type, PresentationSize preferredPresentationSize = { }) = 0;
151
    virtual bool readImage(Ref<FragmentedSharedBuffer>&&, const String& type, PresentationSize preferredPresentationSize = { }) = 0;
151
    virtual bool readURL(const URL&, const String& title) = 0;
152
    virtual bool readURL(const URL&, const String& title) = 0;
152
    virtual bool readPlainText(const String&) = 0;
153
    virtual bool readPlainText(const String&) = 0;
153
#endif
154
#endif
154
155
155
#if PLATFORM(COCOA)
156
#if PLATFORM(COCOA)
156
    virtual bool readWebArchive(SharedBuffer&) = 0;
157
    virtual bool readWebArchive(FragmentedSharedBuffer&) = 0;
157
    virtual bool readRTFD(SharedBuffer&) = 0;
158
    virtual bool readRTFD(FragmentedSharedBuffer&) = 0;
158
    virtual bool readRTF(SharedBuffer&) = 0;
159
    virtual bool readRTF(FragmentedSharedBuffer&) = 0;
159
    virtual bool readDataBuffer(SharedBuffer&, const String& type, const String& name, PresentationSize preferredPresentationSize = { }) = 0;
160
    virtual bool readDataBuffer(FragmentedSharedBuffer&, const String& type, const String& name, PresentationSize preferredPresentationSize = { }) = 0;
160
#endif
161
#endif
161
};
162
};
162
163
Lines 171-177 struct PasteboardFileReader { a/Source/WebCore/platform/Pasteboard.h_sec3
171
    virtual ~PasteboardFileReader() = default;
172
    virtual ~PasteboardFileReader() = default;
172
    virtual void readFilename(const String&) = 0;
173
    virtual void readFilename(const String&) = 0;
173
    virtual bool shouldReadBuffer(const String& /* type */) const { return true; }
174
    virtual bool shouldReadBuffer(const String& /* type */) const { return true; }
174
    virtual void readBuffer(const String& filename, const String& type, Ref<SharedBuffer>&&) = 0;
175
    virtual void readBuffer(const String& filename, const String& type, Ref<FragmentedSharedBuffer>&&) = 0;
175
};
176
};
176
177
177
class Pasteboard {
178
class Pasteboard {
Lines 296-302 public: a/Source/WebCore/platform/Pasteboard.h_sec4
296
    std::optional<PasteboardItemInfo> pasteboardItemInfo(size_t index) const;
297
    std::optional<PasteboardItemInfo> pasteboardItemInfo(size_t index) const;
297
298
298
    String readString(size_t index, const String& type);
299
    String readString(size_t index, const String& type);
299
    RefPtr<WebCore::SharedBuffer> readBuffer(size_t index, const String& type);
300
    RefPtr<WebCore::FragmentedSharedBuffer> readBuffer(size_t index, const String& type);
300
    URL readURL(size_t index, String& title);
301
    URL readURL(size_t index, String& title);
301
302
302
    const PasteboardContext* context() const { return m_context.get(); }
303
    const PasteboardContext* context() const { return m_context.get(); }
- a/Source/WebCore/platform/PasteboardCustomData.cpp -9 / +9 lines
Lines 33-45 a/Source/WebCore/platform/PasteboardCustomData.cpp_sec1
33
33
34
namespace WebCore {
34
namespace WebCore {
35
35
36
static std::variant<String, Ref<SharedBuffer>> copyPlatformData(const std::variant<String, Ref<SharedBuffer>>& other)
36
static std::variant<String, Ref<FragmentedSharedBuffer>> copyPlatformData(const std::variant<String, Ref<FragmentedSharedBuffer>>& other)
37
{
37
{
38
    if (std::holds_alternative<String>(other))
38
    if (std::holds_alternative<String>(other))
39
        return { std::get<String>(other) };
39
        return { std::get<String>(other) };
40
40
41
    if (std::holds_alternative<Ref<SharedBuffer>>(other))
41
    if (std::holds_alternative<Ref<FragmentedSharedBuffer>>(other))
42
        return { std::get<Ref<SharedBuffer>>(other).copyRef() };
42
        return { std::get<Ref<FragmentedSharedBuffer>>(other).copyRef() };
43
43
44
    return { };
44
    return { };
45
}
45
}
Lines 134-140 void PasteboardCustomData::writeString(const String& type, const String& value) a/Source/WebCore/platform/PasteboardCustomData.cpp_sec2
134
    addOrMoveEntryToEnd(type).platformData = { value };
134
    addOrMoveEntryToEnd(type).platformData = { value };
135
}
135
}
136
136
137
void PasteboardCustomData::writeData(const String& type, Ref<SharedBuffer>&& data)
137
void PasteboardCustomData::writeData(const String& type, Ref<FragmentedSharedBuffer>&& data)
138
{
138
{
139
    addOrMoveEntryToEnd(type).platformData = { WTFMove(data) };
139
    addOrMoveEntryToEnd(type).platformData = { WTFMove(data) };
140
}
140
}
Lines 202-215 HashMap<String, String> PasteboardCustomData::sameOriginCustomStringData() const a/Source/WebCore/platform/PasteboardCustomData.cpp_sec3
202
    return customData;
202
    return customData;
203
}
203
}
204
204
205
RefPtr<SharedBuffer> PasteboardCustomData::readBuffer(const String& type) const
205
RefPtr<FragmentedSharedBuffer> PasteboardCustomData::readBuffer(const String& type) const
206
{
206
{
207
    for (auto& entry : m_data) {
207
    for (auto& entry : m_data) {
208
        if (entry.type != type)
208
        if (entry.type != type)
209
            continue;
209
            continue;
210
210
211
        if (std::holds_alternative<Ref<SharedBuffer>>(entry.platformData))
211
        if (std::holds_alternative<Ref<FragmentedSharedBuffer>>(entry.platformData))
212
            return std::get<Ref<SharedBuffer>>(entry.platformData).copyRef();
212
            return std::get<Ref<FragmentedSharedBuffer>>(entry.platformData).copyRef();
213
213
214
        return nullptr;
214
        return nullptr;
215
    }
215
    }
Lines 265-275 void PasteboardCustomData::forEachCustomString(Function<void(const String& type, a/Source/WebCore/platform/PasteboardCustomData.cpp_sec4
265
    }
265
    }
266
}
266
}
267
267
268
void PasteboardCustomData::forEachPlatformStringOrBuffer(Function<void(const String& type, const std::variant<String, Ref<SharedBuffer>>& data)>&& function) const
268
void PasteboardCustomData::forEachPlatformStringOrBuffer(Function<void(const String& type, const std::variant<String, Ref<FragmentedSharedBuffer>>& data)>&& function) const
269
{
269
{
270
    for (auto& entry : m_data) {
270
    for (auto& entry : m_data) {
271
        auto& data = entry.platformData;
271
        auto& data = entry.platformData;
272
        if ((std::holds_alternative<String>(data) && !std::get<String>(data).isNull()) || std::holds_alternative<Ref<SharedBuffer>>(data))
272
        if ((std::holds_alternative<String>(data) && !std::get<String>(data).isNull()) || std::holds_alternative<Ref<FragmentedSharedBuffer>>(data))
273
            function(entry.type, data);
273
            function(entry.type, data);
274
    }
274
    }
275
}
275
}
- a/Source/WebCore/platform/PasteboardCustomData.h -4 / +5 lines
Lines 35-40 a/Source/WebCore/platform/PasteboardCustomData.h_sec1
35
namespace WebCore {
35
namespace WebCore {
36
36
37
class SharedBuffer;
37
class SharedBuffer;
38
class FragmentedSharedBuffer;
38
39
39
class PasteboardCustomData {
40
class PasteboardCustomData {
40
public:
41
public:
Lines 48-54 public: a/Source/WebCore/platform/PasteboardCustomData.h_sec2
48
49
49
        String type;
50
        String type;
50
        String customData;
51
        String customData;
51
        std::variant<String, Ref<SharedBuffer>> platformData;
52
        std::variant<String, Ref<FragmentedSharedBuffer>> platformData;
52
    };
53
    };
53
54
54
    WEBCORE_EXPORT PasteboardCustomData();
55
    WEBCORE_EXPORT PasteboardCustomData();
Lines 65-75 public: a/Source/WebCore/platform/PasteboardCustomData.h_sec3
65
    WEBCORE_EXPORT static PasteboardCustomData fromPersistenceDecoder(WTF::Persistence::Decoder&&);
66
    WEBCORE_EXPORT static PasteboardCustomData fromPersistenceDecoder(WTF::Persistence::Decoder&&);
66
67
67
    String readString(const String& type) const;
68
    String readString(const String& type) const;
68
    RefPtr<SharedBuffer> readBuffer(const String& type) const;
69
    RefPtr<FragmentedSharedBuffer> readBuffer(const String& type) const;
69
    String readStringInCustomData(const String& type) const;
70
    String readStringInCustomData(const String& type) const;
70
71
71
    void writeString(const String& type, const String& value);
72
    void writeString(const String& type, const String& value);
72
    void writeData(const String& type, Ref<SharedBuffer>&& data);
73
    void writeData(const String& type, Ref<FragmentedSharedBuffer>&& data);
73
    void writeStringInCustomData(const String& type, const String& value);
74
    void writeStringInCustomData(const String& type, const String& value);
74
75
75
    void clear();
76
    void clear();
Lines 83-89 public: a/Source/WebCore/platform/PasteboardCustomData.h_sec4
83
84
84
    void forEachType(Function<void(const String&)>&&) const;
85
    void forEachType(Function<void(const String&)>&&) const;
85
    void forEachPlatformString(Function<void(const String& type, const String& data)>&&) const;
86
    void forEachPlatformString(Function<void(const String& type, const String& data)>&&) const;
86
    void forEachPlatformStringOrBuffer(Function<void(const String& type, const std::variant<String, Ref<SharedBuffer>>& data)>&&) const;
87
    void forEachPlatformStringOrBuffer(Function<void(const String& type, const std::variant<String, Ref<FragmentedSharedBuffer>>& data)>&&) const;
87
    void forEachCustomString(Function<void(const String& type, const String& data)>&&) const;
88
    void forEachCustomString(Function<void(const String& type, const String& data)>&&) const;
88
89
89
    bool hasData() const;
90
    bool hasData() const;
- a/Source/WebCore/platform/PasteboardStrategy.h -2 / +3 lines
Lines 31-40 a/Source/WebCore/platform/PasteboardStrategy.h_sec1
31
namespace WebCore {
31
namespace WebCore {
32
32
33
class Color;
33
class Color;
34
class SharedBuffer;
34
class PasteboardContext;
35
class PasteboardContext;
35
class PasteboardCustomData;
36
class PasteboardCustomData;
36
class SelectionData;
37
class SelectionData;
37
class SharedBuffer;
38
class FragmentedSharedBuffer;
38
struct PasteboardImage;
39
struct PasteboardImage;
39
struct PasteboardItemInfo;
40
struct PasteboardItemInfo;
40
struct PasteboardURL;
41
struct PasteboardURL;
Lines 62-68 public: a/Source/WebCore/platform/PasteboardStrategy.h_sec2
62
63
63
    virtual int64_t addTypes(const Vector<String>& pasteboardTypes, const String& pasteboardName, const PasteboardContext*) = 0;
64
    virtual int64_t addTypes(const Vector<String>& pasteboardTypes, const String& pasteboardName, const PasteboardContext*) = 0;
64
    virtual int64_t setTypes(const Vector<String>& pasteboardTypes, const String& pasteboardName, const PasteboardContext*) = 0;
65
    virtual int64_t setTypes(const Vector<String>& pasteboardTypes, const String& pasteboardName, const PasteboardContext*) = 0;
65
    virtual int64_t setBufferForType(SharedBuffer*, const String& pasteboardType, const String& pasteboardName, const PasteboardContext*) = 0;
66
    virtual int64_t setBufferForType(FragmentedSharedBuffer*, const String& pasteboardType, const String& pasteboardName, const PasteboardContext*) = 0;
66
    virtual int64_t setURL(const PasteboardURL&, const String& pasteboardName, const PasteboardContext*) = 0;
67
    virtual int64_t setURL(const PasteboardURL&, const String& pasteboardName, const PasteboardContext*) = 0;
67
    virtual int64_t setColor(const Color&, const String& pasteboardName, const PasteboardContext*) = 0;
68
    virtual int64_t setColor(const Color&, const String& pasteboardName, const PasteboardContext*) = 0;
68
    virtual int64_t setStringForType(const String&, const String& pasteboardType, const String& pasteboardName, const PasteboardContext*) = 0;
69
    virtual int64_t setStringForType(const String&, const String& pasteboardType, const String& pasteboardName, const PasteboardContext*) = 0;
- a/Source/WebCore/platform/PlatformContentFilter.h -2 / +2 lines
Lines 34-40 namespace WebCore { a/Source/WebCore/platform/PlatformContentFilter.h_sec1
34
class ContentFilterUnblockHandler;
34
class ContentFilterUnblockHandler;
35
class ResourceRequest;
35
class ResourceRequest;
36
class ResourceResponse;
36
class ResourceResponse;
37
class SharedBuffer;
37
class FragmentedSharedBuffer;
38
38
39
class PlatformContentFilter {
39
class PlatformContentFilter {
40
    WTF_MAKE_FAST_ALLOCATED;
40
    WTF_MAKE_FAST_ALLOCATED;
Lines 56-62 public: a/Source/WebCore/platform/PlatformContentFilter.h_sec2
56
    virtual void responseReceived(const ResourceResponse&) = 0;
56
    virtual void responseReceived(const ResourceResponse&) = 0;
57
    virtual void addData(const uint8_t* data, int length) = 0;
57
    virtual void addData(const uint8_t* data, int length) = 0;
58
    virtual void finishedAddingData() = 0;
58
    virtual void finishedAddingData() = 0;
59
    virtual Ref<SharedBuffer> replacementData() const = 0;
59
    virtual Ref<FragmentedSharedBuffer> replacementData() const = 0;
60
#if ENABLE(CONTENT_FILTERING)
60
#if ENABLE(CONTENT_FILTERING)
61
    virtual ContentFilterUnblockHandler unblockHandler() const = 0;
61
    virtual ContentFilterUnblockHandler unblockHandler() const = 0;
62
#endif
62
#endif
- a/Source/WebCore/platform/PlatformPasteboard.h -2 / +3 lines
Lines 47-59 struct wpe_pasteboard; a/Source/WebCore/platform/PlatformPasteboard.h_sec1
47
namespace WebCore {
47
namespace WebCore {
48
48
49
class Color;
49
class Color;
50
class SharedBuffer;
50
class PasteboardCustomData;
51
class PasteboardCustomData;
51
class SelectionData;
52
class SelectionData;
52
class SharedBuffer;
53
struct PasteboardImage;
53
struct PasteboardImage;
54
struct PasteboardItemInfo;
54
struct PasteboardItemInfo;
55
struct PasteboardURL;
55
struct PasteboardURL;
56
struct PasteboardWebContent;
56
struct PasteboardWebContent;
57
class FragmentedSharedBuffer;
57
58
58
class PlatformPasteboard {
59
class PlatformPasteboard {
59
public:
60
public:
Lines 85-91 public: a/Source/WebCore/platform/PlatformPasteboard.h_sec2
85
86
86
    // These methods will return 0 if pasteboard ownership has been taken from us.
87
    // These methods will return 0 if pasteboard ownership has been taken from us.
87
    WEBCORE_EXPORT int64_t copy(const String& fromPasteboard);
88
    WEBCORE_EXPORT int64_t copy(const String& fromPasteboard);
88
    WEBCORE_EXPORT int64_t setBufferForType(SharedBuffer*, const String& pasteboardType);
89
    WEBCORE_EXPORT int64_t setBufferForType(FragmentedSharedBuffer*, const String& pasteboardType);
89
    WEBCORE_EXPORT int64_t setURL(const PasteboardURL&);
90
    WEBCORE_EXPORT int64_t setURL(const PasteboardURL&);
90
    WEBCORE_EXPORT int64_t setColor(const Color&);
91
    WEBCORE_EXPORT int64_t setColor(const Color&);
91
    WEBCORE_EXPORT int64_t setStringForType(const String&, const String& pasteboardType);
92
    WEBCORE_EXPORT int64_t setStringForType(const String&, const String& pasteboardType);
- a/Source/WebCore/platform/PreviewConverter.cpp -10 / +7 lines
Lines 63-71 const ResourceError& PreviewConverter::previewError() const a/Source/WebCore/platform/PreviewConverter.cpp_sec1
63
    return m_previewError;
63
    return m_previewError;
64
}
64
}
65
65
66
const SharedBuffer& PreviewConverter::previewData() const
66
const FragmentedSharedBuffer& PreviewConverter::previewData() const
67
{
67
{
68
    return m_previewData.get();
68
    return *m_previewData->get();
69
}
69
}
70
70
71
void PreviewConverter::updateMainResource()
71
void PreviewConverter::updateMainResource()
Lines 82-96 void PreviewConverter::updateMainResource() a/Source/WebCore/platform/PreviewConverter.cpp_sec2
82
        return;
82
        return;
83
    }
83
    }
84
84
85
    provider->provideMainResourceForPreviewConverter(*this, [this, protectedThis = Ref { *this }](auto buffer) {
85
    provider->provideMainResourceForPreviewConverter(*this, [this, protectedThis = Ref { *this }](auto&& buffer) {
86
        if (buffer)
86
        appendFromBuffer(WTFMove(buffer));
87
            appendFromBuffer(*buffer);
88
        else
89
            didFailUpdating();
90
    });
87
    });
91
}
88
}
92
89
93
void PreviewConverter::appendFromBuffer(const SharedBuffer& buffer)
90
void PreviewConverter::appendFromBuffer(const FragmentedSharedBuffer& buffer)
94
{
91
{
95
    while (buffer.size() > m_lengthAppended) {
92
    while (buffer.size() > m_lengthAppended) {
96
        auto newData = buffer.getSomeData(m_lengthAppended);
93
        auto newData = buffer.getSomeData(m_lengthAppended);
Lines 222-228 void PreviewConverter::replayToClient(PreviewConverterClient& client) a/Source/WebCore/platform/PreviewConverter.cpp_sec3
222
    client.previewConverterDidStartConverting(*this);
219
    client.previewConverterDidStartConverting(*this);
223
220
224
    if (!m_previewData->isEmpty() && hasClient(client))
221
    if (!m_previewData->isEmpty() && hasClient(client))
225
        client.previewConverterDidReceiveData(*this, m_previewData.get());
222
        client.previewConverterDidReceiveData(*this, *m_previewData->get());
226
223
227
    if (m_state == State::Converting || !hasClient(client))
224
    if (m_state == State::Converting || !hasClient(client))
228
        return;
225
        return;
Lines 239-245 void PreviewConverter::replayToClient(PreviewConverterClient& client) a/Source/WebCore/platform/PreviewConverter.cpp_sec4
239
    client.previewConverterDidFinishConverting(*this);
236
    client.previewConverterDidFinishConverting(*this);
240
}
237
}
241
238
242
void PreviewConverter::delegateDidReceiveData(const SharedBuffer& data)
239
void PreviewConverter::delegateDidReceiveData(const FragmentedSharedBuffer& data)
243
{
240
{
244
    auto protectedThis { Ref { *this } };
241
    auto protectedThis { Ref { *this } };
245
242
- a/Source/WebCore/platform/PreviewConverter.h -6 / +8 lines
Lines 31-36 a/Source/WebCore/platform/PreviewConverter.h_sec1
31
#include "ResourceResponse.h"
31
#include "ResourceResponse.h"
32
#include <wtf/RefCounted.h>
32
#include <wtf/RefCounted.h>
33
#include <wtf/RetainPtr.h>
33
#include <wtf/RetainPtr.h>
34
#include <wtf/UniqueRef.h>
34
#include <wtf/WeakPtr.h>
35
#include <wtf/WeakPtr.h>
35
#include <wtf/text/WTFString.h>
36
#include <wtf/text/WTFString.h>
36
37
Lines 41-55 namespace WebCore { a/Source/WebCore/platform/PreviewConverter.h_sec2
41
42
42
class ResourceError;
43
class ResourceError;
43
class ResourceRequest;
44
class ResourceRequest;
44
class SharedBuffer;
45
class FragmentedSharedBuffer;
45
class SharedBufferDataView;
46
class SharedBufferDataView;
47
class SharedBufferBuilder;
46
struct PreviewConverterClient;
48
struct PreviewConverterClient;
47
struct PreviewConverterProvider;
49
struct PreviewConverterProvider;
48
50
49
struct PreviewPlatformDelegate : CanMakeWeakPtr<PreviewPlatformDelegate> {
51
struct PreviewPlatformDelegate : CanMakeWeakPtr<PreviewPlatformDelegate> {
50
    virtual ~PreviewPlatformDelegate() = default;
52
    virtual ~PreviewPlatformDelegate() = default;
51
53
52
    virtual void delegateDidReceiveData(const SharedBuffer&) = 0;
54
    virtual void delegateDidReceiveData(const FragmentedSharedBuffer&) = 0;
53
    virtual void delegateDidFinishLoading() = 0;
55
    virtual void delegateDidFinishLoading() = 0;
54
    virtual void delegateDidFailWithError(const ResourceError&) = 0;
56
    virtual void delegateDidFailWithError(const ResourceError&) = 0;
55
};
57
};
Lines 72-78 public: a/Source/WebCore/platform/PreviewConverter.h_sec3
72
    WEBCORE_EXPORT String previewFileName() const;
74
    WEBCORE_EXPORT String previewFileName() const;
73
    WEBCORE_EXPORT String previewUTI() const;
75
    WEBCORE_EXPORT String previewUTI() const;
74
    const ResourceError& previewError() const;
76
    const ResourceError& previewError() const;
75
    const SharedBuffer& previewData() const;
77
    const FragmentedSharedBuffer& previewData() const;
76
78
77
    void failedUpdating();
79
    void failedUpdating();
78
    void finishUpdating();
80
    void finishUpdating();
Lines 94-100 private: a/Source/WebCore/platform/PreviewConverter.h_sec4
94
    bool isPlatformPasswordError(const ResourceError&) const;
96
    bool isPlatformPasswordError(const ResourceError&) const;
95
97
96
    template<typename T> void iterateClients(T&& callback);
98
    template<typename T> void iterateClients(T&& callback);
97
    void appendFromBuffer(const SharedBuffer&);
99
    void appendFromBuffer(const FragmentedSharedBuffer&);
98
    void didAddClient(PreviewConverterClient&);
100
    void didAddClient(PreviewConverterClient&);
99
    void didFailConvertingWithError(const ResourceError&);
101
    void didFailConvertingWithError(const ResourceError&);
100
    void didFailUpdating();
102
    void didFailUpdating();
Lines 106-112 private: a/Source/WebCore/platform/PreviewConverter.h_sec5
106
    void platformUnlockWithPassword(const String&);
108
    void platformUnlockWithPassword(const String&);
107
109
108
    // PreviewPlatformDelegate
110
    // PreviewPlatformDelegate
109
    void delegateDidReceiveData(const SharedBuffer&) final;
111
    void delegateDidReceiveData(const FragmentedSharedBuffer&) final;
110
    void delegateDidFinishLoading() final;
112
    void delegateDidFinishLoading() final;
111
    void delegateDidFailWithError(const ResourceError&) final;
113
    void delegateDidFailWithError(const ResourceError&) final;
112
114
Lines 118-124 private: a/Source/WebCore/platform/PreviewConverter.h_sec6
118
        FinishedConverting,
120
        FinishedConverting,
119
    };
121
    };
120
122
121
    Ref<SharedBuffer> m_previewData;
123
    UniqueRef<SharedBufferBuilder> m_previewData;
122
    ResourceError m_previewError;
124
    ResourceError m_previewError;
123
    ResourceResponse m_originalResponse;
125
    ResourceResponse m_originalResponse;
124
    State m_state { State::Updating };
126
    State m_state { State::Updating };
- a/Source/WebCore/platform/PreviewConverterClient.h -2 / +2 lines
Lines 33-39 namespace WebCore { a/Source/WebCore/platform/PreviewConverterClient.h_sec1
33
33
34
class PreviewConverter;
34
class PreviewConverter;
35
class ResourceError;
35
class ResourceError;
36
class SharedBuffer;
36
class FragmentedSharedBuffer;
37
37
38
struct PreviewConverterClient : CanMakeWeakPtr<PreviewConverterClient> {
38
struct PreviewConverterClient : CanMakeWeakPtr<PreviewConverterClient> {
39
    virtual ~PreviewConverterClient() = default;
39
    virtual ~PreviewConverterClient() = default;
Lines 42-48 struct PreviewConverterClient : CanMakeWeakPtr<PreviewConverterClient> { a/Source/WebCore/platform/PreviewConverterClient.h_sec2
42
    virtual void previewConverterDidFinishUpdating(PreviewConverter&) = 0;
42
    virtual void previewConverterDidFinishUpdating(PreviewConverter&) = 0;
43
    virtual void previewConverterDidFailUpdating(PreviewConverter&) = 0;
43
    virtual void previewConverterDidFailUpdating(PreviewConverter&) = 0;
44
    virtual void previewConverterDidStartConverting(PreviewConverter&) = 0;
44
    virtual void previewConverterDidStartConverting(PreviewConverter&) = 0;
45
    virtual void previewConverterDidReceiveData(PreviewConverter&, const SharedBuffer& newData) = 0;
45
    virtual void previewConverterDidReceiveData(PreviewConverter&, const FragmentedSharedBuffer& newData) = 0;
46
    virtual void previewConverterDidFinishConverting(PreviewConverter&) = 0;
46
    virtual void previewConverterDidFinishConverting(PreviewConverter&) = 0;
47
    virtual void previewConverterDidFailConverting(PreviewConverter&) = 0;
47
    virtual void previewConverterDidFailConverting(PreviewConverter&) = 0;
48
};
48
};
- a/Source/WebCore/platform/PreviewConverterProvider.h -1 / +1 lines
Lines 32-38 namespace WebCore { a/Source/WebCore/platform/PreviewConverterProvider.h_sec1
32
struct PreviewConverterProvider : CanMakeWeakPtr<PreviewConverterProvider> {
32
struct PreviewConverterProvider : CanMakeWeakPtr<PreviewConverterProvider> {
33
    virtual ~PreviewConverterProvider() = default;
33
    virtual ~PreviewConverterProvider() = default;
34
34
35
    virtual void provideMainResourceForPreviewConverter(PreviewConverter&, CompletionHandler<void(const SharedBuffer*)>&&) = 0;
35
    virtual void provideMainResourceForPreviewConverter(PreviewConverter&, CompletionHandler<void(Ref<FragmentedSharedBuffer>&&)>&&) = 0;
36
    virtual void providePasswordForPreviewConverter(PreviewConverter&, CompletionHandler<void(const String&)>&&) = 0;
36
    virtual void providePasswordForPreviewConverter(PreviewConverter&, CompletionHandler<void(const String&)>&&) = 0;
37
};
37
};
38
38
- a/Source/WebCore/platform/SharedBuffer.cpp -134 / +187 lines
Lines 37-99 a/Source/WebCore/platform/SharedBuffer.cpp_sec1
37
37
38
namespace WebCore {
38
namespace WebCore {
39
39
40
SharedBuffer::SharedBuffer(const uint8_t* data, size_t size)
40
Ref<FragmentedSharedBuffer> FragmentedSharedBuffer::create()
41
{
41
{
42
    append(data, size);
42
    return adoptRef(*new FragmentedSharedBuffer);
43
}
43
}
44
44
45
SharedBuffer::SharedBuffer(const char* data, size_t size)
45
Ref<FragmentedSharedBuffer> FragmentedSharedBuffer::create(const uint8_t* data, size_t size)
46
{
46
{
47
    append(reinterpret_cast<const uint8_t*>(data), size);
47
    return adoptRef(*new FragmentedSharedBuffer(data, size));
48
}
48
}
49
49
50
SharedBuffer::SharedBuffer(FileSystem::MappedFileData&& fileData)
50
Ref<FragmentedSharedBuffer> FragmentedSharedBuffer::create(FileSystem::MappedFileData&& mappedFileData)
51
    : m_size(fileData.size())
52
{
51
{
53
    m_segments.append({0, DataSegment::create(WTFMove(fileData))});
52
    return adoptRef(*new FragmentedSharedBuffer(WTFMove(mappedFileData)));
54
}
53
}
55
54
56
SharedBuffer::SharedBuffer(DataSegment::Provider&& provider)
55
Ref<FragmentedSharedBuffer> FragmentedSharedBuffer::create(Ref<SharedBuffer>&& buffer)
57
    : m_size(provider.size())
58
{
56
{
59
    m_segments.append({0, DataSegment::create(WTFMove(provider))});
57
    return adoptRef(*new FragmentedSharedBuffer(WTFMove(buffer)));
60
}
58
}
61
59
62
SharedBuffer::SharedBuffer(Vector<uint8_t>&& data)
60
Ref<FragmentedSharedBuffer> FragmentedSharedBuffer::create(Vector<uint8_t>&& vector)
63
{
61
{
64
    append(WTFMove(data));
62
    return adoptRef(*new FragmentedSharedBuffer(WTFMove(vector)));
65
}
63
}
66
64
67
#if USE(GSTREAMER)
65
Ref<FragmentedSharedBuffer> FragmentedSharedBuffer::create(DataSegment::Provider&& provider)
68
Ref<SharedBuffer> SharedBuffer::create(GstMappedOwnedBuffer& mappedBuffer)
69
{
66
{
70
    return adoptRef(*new SharedBuffer(mappedBuffer));
67
    return adoptRef(*new FragmentedSharedBuffer(WTFMove(provider)));
71
}
68
}
72
69
73
SharedBuffer::SharedBuffer(GstMappedOwnedBuffer& mappedBuffer)
70
FragmentedSharedBuffer::FragmentedSharedBuffer() = default;
74
    : m_size(mappedBuffer.size())
71
72
FragmentedSharedBuffer::FragmentedSharedBuffer(FileSystem::MappedFileData&& fileData)
73
    : m_size(fileData.size())
75
{
74
{
76
    m_segments.append({0, DataSegment::create(&mappedBuffer)});
75
    m_segments.append({ 0, DataSegment::create(WTFMove(fileData)) });
77
}
76
}
78
#endif
79
77
80
RefPtr<SharedBuffer> SharedBuffer::createWithContentsOfFile(const String& filePath, FileSystem::MappedFileMode mappedFileMode, MayUseFileMapping mayUseFileMapping)
78
FragmentedSharedBuffer::FragmentedSharedBuffer(DataSegment::Provider&& provider)
79
    : m_size(provider.size())
81
{
80
{
82
    if (mayUseFileMapping == MayUseFileMapping::Yes) {
81
    m_segments.append({ 0, DataSegment::create(WTFMove(provider)) });
83
        bool mappingSuccess;
84
        FileSystem::MappedFileData mappedFileData(filePath, mappedFileMode, mappingSuccess);
85
        if (mappingSuccess)
86
            return adoptRef(new SharedBuffer(WTFMove(mappedFileData)));
87
    }
88
    return SharedBuffer::createFromReadingFile(filePath);
89
}
82
}
90
83
91
Ref<SharedBuffer> SharedBuffer::create(Vector<uint8_t>&& vector)
84
FragmentedSharedBuffer::FragmentedSharedBuffer(Ref<SharedBuffer>&& buffer)
92
{
85
{
93
    return adoptRef(*new SharedBuffer(WTFMove(vector)));
86
    append(WTFMove(buffer));
94
}
87
}
95
88
96
static Vector<uint8_t> combineSegmentsData(const SharedBuffer::DataSegmentVector& segments, size_t size)
89
#if USE(GSTREAMER)
90
Ref<FragmentedSharedBuffer> FragmentedSharedBuffer::create(GstMappedOwnedBuffer& mappedBuffer)
91
{
92
    return adoptRef(*new FragmentedSharedBuffer(mappedBuffer));
93
}
94
95
FragmentedSharedBuffer::FragmentedSharedBuffer(GstMappedOwnedBuffer& mappedBuffer)
96
    : m_size(mappedBuffer.size())
97
{
98
    m_segments.append({ 0, DataSegment::create(&mappedBuffer) });
99
}
100
#endif
101
102
static Vector<uint8_t> combineSegmentsData(const FragmentedSharedBuffer::DataSegmentVector& segments, size_t size)
97
{
103
{
98
    Vector<uint8_t> combinedData;
104
    Vector<uint8_t> combinedData;
99
    combinedData.reserveInitialCapacity(size);
105
    combinedData.reserveInitialCapacity(size);
Lines 103-135 static Vector<uint8_t> combineSegmentsData(const SharedBuffer::DataSegmentVector a/Source/WebCore/platform/SharedBuffer.cpp_sec2
103
    return combinedData;
109
    return combinedData;
104
}
110
}
105
111
106
void SharedBuffer::combineIntoOneSegment() const
112
Ref<SharedBuffer> FragmentedSharedBuffer::makeContiguous() const
107
{
113
{
108
#if ASSERT_ENABLED
114
    if (m_contiguous)
109
    // FIXME: We ought to be able to set this to true and have no assertions fire.
115
        return Ref { *static_cast<SharedBuffer*>(const_cast<FragmentedSharedBuffer*>(this)) };
110
    // Remove all instances of appending after calling this, because they are all O(n^2) algorithms since r215686.
116
    if (!m_segments.size())
111
    // m_hasBeenCombinedIntoOneSegment = true;
117
        return SharedBuffer::create();
112
#endif
118
    if (m_segments.size() == 1)
113
    if (m_segments.size() <= 1)
119
        return SharedBuffer::create(m_segments[0].segment.copyRef());
114
        return;
115
116
    auto combinedData = combineSegmentsData(m_segments, m_size);
120
    auto combinedData = combineSegmentsData(m_segments, m_size);
117
    m_segments.clear();
121
    return SharedBuffer::create(WTFMove(combinedData));
118
    m_segments.append({0, DataSegment::create(WTFMove(combinedData))});
119
    ASSERT(m_segments.size() == 1);
120
    ASSERT(internallyConsistent());
121
}
122
}
122
123
123
const uint8_t* SharedBuffer::data() const
124
Vector<uint8_t> FragmentedSharedBuffer::copyData() const
124
{
125
    if (m_segments.isEmpty())
126
        return nullptr;
127
    combineIntoOneSegment();
128
    ASSERT(internallyConsistent());
129
    return m_segments[0].segment->data();
130
}
131
132
Vector<uint8_t> SharedBuffer::copyData() const
133
{
125
{
134
    Vector<uint8_t> data;
126
    Vector<uint8_t> data;
135
    data.reserveInitialCapacity(size());
127
    data.reserveInitialCapacity(size());
Lines 139-145 Vector<uint8_t> SharedBuffer::copyData() const a/Source/WebCore/platform/SharedBuffer.cpp_sec3
139
    return data;
131
    return data;
140
}
132
}
141
133
142
Vector<uint8_t> SharedBuffer::takeData()
134
Vector<uint8_t> FragmentedSharedBuffer::takeData()
143
{
135
{
144
    if (m_segments.isEmpty())
136
    if (m_segments.isEmpty())
145
        return { };
137
        return { };
Lines 154-166 Vector<uint8_t> SharedBuffer::takeData() a/Source/WebCore/platform/SharedBuffer.cpp_sec4
154
    return combinedData;
146
    return combinedData;
155
}
147
}
156
148
157
SharedBufferDataView SharedBuffer::getSomeData(size_t position) const
149
SharedBufferDataView FragmentedSharedBuffer::getSomeData(size_t position) const
158
{
150
{
159
    const DataSegmentVectorEntry* element = getSegmentForPosition(position);
151
    const DataSegmentVectorEntry* element = getSegmentForPosition(position);
160
    return { element->segment.copyRef(), position - element->beginPosition };
152
    return { element->segment.copyRef(), position - element->beginPosition };
161
}
153
}
162
154
163
const SharedBuffer::DataSegmentVectorEntry* SharedBuffer::getSegmentForPosition(size_t position) const
155
const FragmentedSharedBuffer::DataSegmentVectorEntry* FragmentedSharedBuffer::getSegmentForPosition(size_t position) const
164
{
156
{
165
    RELEASE_ASSERT(position < m_size);
157
    RELEASE_ASSERT(position < m_size);
166
    auto comparator = [](const size_t& position, const DataSegmentVectorEntry& entry) {
158
    auto comparator = [](const size_t& position, const DataSegmentVectorEntry& entry) {
Lines 171-177 const SharedBuffer::DataSegmentVectorEntry* SharedBuffer::getSegmentForPosition( a/Source/WebCore/platform/SharedBuffer.cpp_sec5
171
    return element;
163
    return element;
172
}
164
}
173
165
174
String SharedBuffer::toHexString() const
166
String FragmentedSharedBuffer::toHexString() const
175
{
167
{
176
    StringBuilder stringBuilder;
168
    StringBuilder stringBuilder;
177
    forEachSegment([&](auto& segment) {
169
    forEachSegment([&](auto& segment) {
Lines 181-187 String SharedBuffer::toHexString() const a/Source/WebCore/platform/SharedBuffer.cpp_sec6
181
    return stringBuilder.toString();
173
    return stringBuilder.toString();
182
}
174
}
183
175
184
RefPtr<ArrayBuffer> SharedBuffer::tryCreateArrayBuffer() const
176
RefPtr<ArrayBuffer> FragmentedSharedBuffer::tryCreateArrayBuffer() const
185
{
177
{
186
    auto arrayBuffer = ArrayBuffer::tryCreateUninitialized(static_cast<unsigned>(size()), 1);
178
    auto arrayBuffer = ArrayBuffer::tryCreateUninitialized(static_cast<unsigned>(size()), 1);
187
    if (!arrayBuffer) {
179
    if (!arrayBuffer) {
Lines 200-267 RefPtr<ArrayBuffer> SharedBuffer::tryCreateArrayBuffer() const a/Source/WebCore/platform/SharedBuffer.cpp_sec7
200
    return arrayBuffer;
192
    return arrayBuffer;
201
}
193
}
202
194
203
void SharedBuffer::append(const SharedBuffer& data)
195
void FragmentedSharedBuffer::append(const FragmentedSharedBuffer& data)
204
{
196
{
205
    ASSERT(!m_hasBeenCombinedIntoOneSegment);
197
    ASSERT(!m_contiguous);
206
    m_segments.reserveCapacity(m_segments.size() + data.m_segments.size());
198
    m_segments.reserveCapacity(m_segments.size() + data.m_segments.size());
207
    for (const auto& element : data.m_segments) {
199
    for (const auto& element : data.m_segments) {
208
        m_segments.uncheckedAppend({m_size, element.segment.copyRef()});
200
        m_segments.uncheckedAppend({ m_size, element.segment.copyRef() });
209
        m_size += element.segment->size();
201
        m_size += element.segment->size();
210
    }
202
    }
211
    ASSERT(internallyConsistent());
203
    ASSERT(internallyConsistent());
212
}
204
}
213
205
214
void SharedBuffer::append(const uint8_t* data, size_t length)
206
void FragmentedSharedBuffer::append(const uint8_t* data, size_t length)
215
{
207
{
216
    ASSERT(!m_hasBeenCombinedIntoOneSegment);
208
    ASSERT(!m_contiguous);
217
    Vector<uint8_t> vector;
209
    Vector<uint8_t> vector;
218
    vector.append(data, length);
210
    vector.append(data, length);
219
    m_segments.append({m_size, DataSegment::create(WTFMove(vector))});
211
    m_segments.append({ m_size, DataSegment::create(WTFMove(vector)) });
220
    m_size += length;
212
    m_size += length;
221
    ASSERT(internallyConsistent());
213
    ASSERT(internallyConsistent());
222
}
214
}
223
215
224
void SharedBuffer::append(Vector<uint8_t>&& data)
216
void FragmentedSharedBuffer::append(Vector<uint8_t>&& data)
225
{
217
{
226
    ASSERT(!m_hasBeenCombinedIntoOneSegment);
218
    ASSERT(!m_contiguous);
227
    auto dataSize = data.size();
219
    auto dataSize = data.size();
228
    m_segments.append({m_size, DataSegment::create(WTFMove(data))});
220
    m_segments.append({ m_size, DataSegment::create(WTFMove(data)) });
229
    m_size += dataSize;
221
    m_size += dataSize;
230
    ASSERT(internallyConsistent());
222
    ASSERT(internallyConsistent());
231
}
223
}
232
224
233
void SharedBuffer::clear()
225
void FragmentedSharedBuffer::clear()
234
{
226
{
235
    m_size = 0;
227
    m_size = 0;
236
    m_segments.clear();
228
    m_segments.clear();
237
    ASSERT(internallyConsistent());
229
    ASSERT(internallyConsistent());
238
}
230
}
239
231
240
Ref<SharedBuffer> SharedBuffer::copy() const
232
Ref<FragmentedSharedBuffer> FragmentedSharedBuffer::copy() const
241
{
233
{
242
    Ref<SharedBuffer> clone = adoptRef(*new SharedBuffer);
234
    Ref<FragmentedSharedBuffer> clone = adoptRef(*new FragmentedSharedBuffer);
243
    clone->m_size = m_size;
235
    clone->m_size = m_size;
244
    clone->m_segments.reserveInitialCapacity(m_segments.size());
236
    clone->m_segments.reserveInitialCapacity(m_segments.size());
245
    for (const auto& element : m_segments)
237
    for (const auto& element : m_segments)
246
        clone->m_segments.uncheckedAppend({element.beginPosition, element.segment.copyRef()});
238
        clone->m_segments.uncheckedAppend({ element.beginPosition, element.segment.copyRef() });
247
    ASSERT(clone->internallyConsistent());
239
    ASSERT(clone->internallyConsistent());
248
    ASSERT(internallyConsistent());
240
    ASSERT(internallyConsistent());
249
    return clone;
241
    return clone;
250
}
242
}
251
243
252
Ref<SharedBuffer> SharedBuffer::create(DataSegment::Provider&& provider)
244
void FragmentedSharedBuffer::forEachSegment(const Function<void(const Span<const uint8_t>&)>& apply) const
253
{
254
    return adoptRef(*new SharedBuffer(WTFMove(provider)));
255
}
256
257
void SharedBuffer::forEachSegment(const Function<void(const Span<const uint8_t>&)>& apply) const
258
{
245
{
259
    auto segments = m_segments;
246
    auto segments = m_segments;
260
    for (auto& segment : segments)
247
    for (auto& segment : segments)
261
        apply(Span { segment.segment->data(), segment.segment->size() });
248
        apply(Span { segment.segment->data(), segment.segment->size() });
262
}
249
}
263
250
264
bool SharedBuffer::startsWith(const Span<const uint8_t>& prefix) const
251
bool FragmentedSharedBuffer::startsWith(const Span<const uint8_t>& prefix) const
265
{
252
{
266
    if (prefix.empty())
253
    if (prefix.empty())
267
        return true;
254
        return true;
Lines 283-289 bool SharedBuffer::startsWith(const Span<const uint8_t>& prefix) const a/Source/WebCore/platform/SharedBuffer.cpp_sec8
283
    return false;
270
    return false;
284
}
271
}
285
272
286
Vector<uint8_t> SharedBuffer::read(size_t offset, size_t length) const
273
Vector<uint8_t> FragmentedSharedBuffer::read(size_t offset, size_t length) const
287
{
274
{
288
    Vector<uint8_t> data;
275
    Vector<uint8_t> data;
289
    if (offset >= size())
276
    if (offset >= size())
Lines 310-321 Vector<uint8_t> SharedBuffer::read(size_t offset, size_t length) const a/Source/WebCore/platform/SharedBuffer.cpp_sec9
310
    return data;
297
    return data;
311
}
298
}
312
299
313
void SharedBuffer::copyTo(void* destination, size_t length) const
300
void FragmentedSharedBuffer::copyTo(void* destination, size_t length) const
314
{
301
{
315
    return copyTo(destination, 0, length);
302
    return copyTo(destination, 0, length);
316
}
303
}
317
304
318
void SharedBuffer::copyTo(void* destination, size_t offset, size_t length) const
305
void FragmentedSharedBuffer::copyTo(void* destination, size_t offset, size_t length) const
319
{
306
{
320
    ASSERT(length + offset <= size());
307
    ASSERT(length + offset <= size());
321
    if (offset >= size())
308
    if (offset >= size())
Lines 353-366 void SharedBuffer::copyTo(void* destination, size_t offset, size_t length) const a/Source/WebCore/platform/SharedBuffer.cpp_sec10
353
    }
340
    }
354
}
341
}
355
342
356
bool SharedBuffer::hasOneSegment() const
357
{
358
    auto it = begin();
359
    return it != end() && ++it == end();
360
}
361
362
#if ASSERT_ENABLED
343
#if ASSERT_ENABLED
363
bool SharedBuffer::internallyConsistent() const
344
bool FragmentedSharedBuffer::internallyConsistent() const
364
{
345
{
365
    size_t position = 0;
346
    size_t position = 0;
366
    for (const auto& element : m_segments) {
347
    for (const auto& element : m_segments) {
Lines 372-413 bool SharedBuffer::internallyConsistent() const a/Source/WebCore/platform/SharedBuffer.cpp_sec11
372
}
353
}
373
#endif // ASSERT_ENABLED
354
#endif // ASSERT_ENABLED
374
355
375
const uint8_t* SharedBuffer::DataSegment::data() const
376
{
377
    auto visitor = WTF::makeVisitor(
378
        [](const Vector<uint8_t>& data) -> const uint8_t* { return data.data(); },
379
#if USE(CF)
380
        [](const RetainPtr<CFDataRef>& data) -> const uint8_t* { return CFDataGetBytePtr(data.get()); },
381
#endif
382
#if USE(GLIB)
383
        [](const GRefPtr<GBytes>& data) -> const uint8_t* { return static_cast<const uint8_t*>(g_bytes_get_data(data.get(), nullptr)); },
384
#endif
385
#if USE(GSTREAMER)
386
        [](const RefPtr<GstMappedOwnedBuffer>& data) -> const uint8_t* { return data->data(); },
387
#endif
388
        [](const FileSystem::MappedFileData& data) -> const uint8_t* { return static_cast<const uint8_t*>(data.data()); },
389
        [](const Provider& provider) -> const uint8_t* { return provider.data(); }
390
    );
391
    return std::visit(visitor, m_immutableData);
392
}
393
394
bool SharedBuffer::DataSegment::containsMappedFileData() const
395
{
396
    return std::holds_alternative<FileSystem::MappedFileData>(m_immutableData);
397
}
398
399
#if !USE(CF)
356
#if !USE(CF)
400
void SharedBuffer::hintMemoryNotNeededSoon() const
357
void FragmentedSharedBuffer::hintMemoryNotNeededSoon() const
401
{
358
{
402
}
359
}
403
#endif
360
#endif
404
361
405
WTF::Persistence::Decoder SharedBuffer::decoder() const
362
bool FragmentedSharedBuffer::operator==(const FragmentedSharedBuffer& other) const
406
{
407
    return {{ reinterpret_cast<const uint8_t*>(data()), size() }};
408
}
409
410
bool SharedBuffer::operator==(const SharedBuffer& other) const
411
{
363
{
412
    if (this == &other)
364
    if (this == &other)
413
        return true;
365
        return true;
Lines 456-462 bool SharedBuffer::operator==(const SharedBuffer& other) const a/Source/WebCore/platform/SharedBuffer.cpp_sec12
456
    return true;
408
    return true;
457
}
409
}
458
410
459
size_t SharedBuffer::DataSegment::size() const
411
SharedBuffer::SharedBuffer()
412
{
413
    m_contiguous = true;
414
}
415
416
SharedBuffer::SharedBuffer(Ref<DataSegment>&& segment)
417
{
418
    m_size = segment->size();
419
    m_segments.append({ 0, WTFMove(segment) });
420
    m_contiguous = true;
421
}
422
423
SharedBuffer::SharedBuffer(Ref<FragmentedSharedBuffer>&& contiguousBuffer)
424
{
425
    ASSERT(contiguousBuffer->hasOneSegment() || contiguousBuffer->isEmpty());
426
    m_size = contiguousBuffer->size();
427
    if (contiguousBuffer->hasOneSegment())
428
        m_segments.append({ 0, contiguousBuffer->m_segments[0].segment.copyRef() });
429
    m_contiguous = true;
430
}
431
432
SharedBuffer::SharedBuffer(FileSystem::MappedFileData&& data)
433
    : FragmentedSharedBuffer(WTFMove(data))
434
{
435
    m_contiguous = true;
436
}
437
438
RefPtr<SharedBuffer> SharedBuffer::createWithContentsOfFile(const String& filePath, FileSystem::MappedFileMode mappedFileMode, MayUseFileMapping mayUseFileMapping)
439
{
440
    if (mayUseFileMapping == MayUseFileMapping::Yes) {
441
        bool mappingSuccess;
442
        FileSystem::MappedFileData mappedFileData(filePath, mappedFileMode, mappingSuccess);
443
        if (mappingSuccess)
444
            return adoptRef(new SharedBuffer(WTFMove(mappedFileData)));
445
    }
446
    return createFromReadingFile(filePath);
447
}
448
449
const uint8_t* SharedBuffer::data() const
450
{
451
    if (m_segments.isEmpty())
452
        return nullptr;
453
    return m_segments[0].segment->data();
454
}
455
456
WTF::Persistence::Decoder SharedBuffer::decoder() const
457
{
458
    return { { data(), size() } };
459
}
460
461
Ref<DataSegment> DataSegment::create(Vector<uint8_t>&& data)
462
{
463
    data.shrinkToFit();
464
    return adoptRef(*new DataSegment(WTFMove(data)));
465
}
466
467
#if USE(CF)
468
Ref<DataSegment> DataSegment::create(RetainPtr<CFDataRef>&& data)
469
{
470
    return adoptRef(*new DataSegment(WTFMove(data)));
471
}
472
#endif
473
474
#if USE(GLIB)
475
Ref<DataSegment> DataSegment::create(GRefPtr<GBytes>&& data)
476
{
477
    return adoptRef(*new DataSegment(WTFMove(data)));
478
}
479
#endif
480
481
#if USE(GSTREAMER)
482
Ref<DataSegment> DataSegment::create(RefPtr<GstMappedOwnedBuffer>&& data)
483
{
484
    return adoptRef(*new DataSegment(WTFMove(data)));
485
}
486
#endif
487
488
Ref<DataSegment> DataSegment::create(FileSystem::MappedFileData&& data)
489
{
490
    return adoptRef(*new DataSegment(WTFMove(data)));
491
}
492
493
Ref<DataSegment> DataSegment::create(Provider&& provider)
494
{
495
    return adoptRef(*new DataSegment(WTFMove(provider)));
496
}
497
498
const uint8_t* DataSegment::data() const
499
{
500
    auto visitor = WTF::makeVisitor(
501
        [](const Vector<uint8_t>& data) -> const uint8_t* { return data.data(); },
502
#if USE(CF)
503
        [](const RetainPtr<CFDataRef>& data) -> const uint8_t* { return CFDataGetBytePtr(data.get()); },
504
#endif
505
#if USE(GLIB)
506
        [](const GRefPtr<GBytes>& data) -> const uint8_t* { return static_cast<const uint8_t*>(g_bytes_get_data(data.get(), nullptr)); },
507
#endif
508
#if USE(GSTREAMER)
509
        [](const RefPtr<GstMappedOwnedBuffer>& data) -> const uint8_t* { return data->data(); },
510
#endif
511
        [](const FileSystem::MappedFileData& data) -> const uint8_t* { return static_cast<const uint8_t*>(data.data()); },
512
        [](const Provider& provider) -> const uint8_t* { return provider.data(); }
513
    );
514
    return std::visit(visitor, m_immutableData);
515
}
516
517
bool DataSegment::containsMappedFileData() const
518
{
519
    return std::holds_alternative<FileSystem::MappedFileData>(m_immutableData);
520
}
521
522
size_t DataSegment::size() const
460
{
523
{
461
    auto visitor = WTF::makeVisitor(
524
    auto visitor = WTF::makeVisitor(
462
        [](const Vector<uint8_t>& data) -> size_t { return data.size(); },
525
        [](const Vector<uint8_t>& data) -> size_t { return data.size(); },
Lines 475-481 size_t SharedBuffer::DataSegment::size() const a/Source/WebCore/platform/SharedBuffer.cpp_sec13
475
    return std::visit(visitor, m_immutableData);
538
    return std::visit(visitor, m_immutableData);
476
}
539
}
477
540
478
SharedBufferDataView::SharedBufferDataView(Ref<SharedBuffer::DataSegment>&& segment, size_t positionWithinSegment, std::optional<size_t> size)
541
SharedBufferDataView::SharedBufferDataView(Ref<DataSegment>&& segment, size_t positionWithinSegment, std::optional<size_t> size)
479
    : m_segment(WTFMove(segment))
542
    : m_segment(WTFMove(segment))
480
    , m_positionWithinSegment(positionWithinSegment)
543
    , m_positionWithinSegment(positionWithinSegment)
481
    , m_size(size ? *size : m_segment->size() - positionWithinSegment)
544
    , m_size(size ? *size : m_segment->size() - positionWithinSegment)
Lines 489-510 SharedBufferDataView::SharedBufferDataView(const SharedBufferDataView& other, si a/Source/WebCore/platform/SharedBuffer.cpp_sec14
489
{
552
{
490
}
553
}
491
554
492
size_t SharedBufferDataView::size() const
493
{
494
    return m_size;
495
}
496
497
const uint8_t* SharedBufferDataView::data() const
498
{
499
    return m_segment->data() + m_positionWithinSegment;
500
}
501
502
Ref<SharedBuffer> SharedBufferDataView::createSharedBuffer() const
555
Ref<SharedBuffer> SharedBufferDataView::createSharedBuffer() const
503
{
556
{
504
    const Ref<SharedBuffer::DataSegment> segment = m_segment;
557
    const Ref<DataSegment> segment = m_segment;
505
    return SharedBuffer::create(SharedBuffer::DataSegment::Provider {
558
    return SharedBuffer::create(DataSegment::Provider {
506
        [segment, data = data()]() { return data; },
559
        [segment, data = data()]() { return data; },
507
        [segment, size = size()]() { return size; }
560
        [size = size()]() { return size; }
508
    });
561
    });
509
}
562
}
510
563
- a/Source/WebCore/platform/SharedBuffer.h -137 / +238 lines
Lines 1-5 a/Source/WebCore/platform/SharedBuffer.h_sec1
1
/*
1
/*
2
 * Copyright (C) 2006-2019 Apple Inc. All rights reserved.
2
 * Copyright (C) 2006-2021 Apple Inc. All rights reserved.
3
 * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
3
 * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
4
 *
4
 *
5
 * Redistribution and use in source and binary forms, with or without
5
 * Redistribution and use in source and binary forms, with or without
Lines 62-207 class Decoder; a/Source/WebCore/platform/SharedBuffer.h_sec2
62
62
63
namespace WebCore {
63
namespace WebCore {
64
64
65
class SharedBuffer;
65
class SharedBufferDataView;
66
class SharedBufferDataView;
66
67
67
class WEBCORE_EXPORT SharedBuffer : public ThreadSafeRefCounted<SharedBuffer> {
68
// Data wrapped by a DataSegment should be immutable because it can be referenced by other objects.
69
// To modify or combine the data, allocate a new DataSegment.
70
class DataSegment : public ThreadSafeRefCounted<DataSegment> {
68
public:
71
public:
69
    static Ref<SharedBuffer> create() { return adoptRef(*new SharedBuffer); }
72
    WEBCORE_EXPORT const uint8_t* data() const;
70
    static Ref<SharedBuffer> create(const uint8_t* data, size_t size) { return adoptRef(*new SharedBuffer(data, size)); }
73
    WEBCORE_EXPORT size_t size() const;
71
    static Ref<SharedBuffer> create(const char* data, size_t size) { return adoptRef(*new SharedBuffer(data, size)); }
72
    static Ref<SharedBuffer> create(FileSystem::MappedFileData&& mappedFileData) { return adoptRef(*new SharedBuffer(WTFMove(mappedFileData))); }
73
74
74
    enum class MayUseFileMapping : bool { No, Yes };
75
    WEBCORE_EXPORT static Ref<DataSegment> create(Vector<uint8_t>&&);
75
    static RefPtr<SharedBuffer> createWithContentsOfFile(const String& filePath, FileSystem::MappedFileMode = FileSystem::MappedFileMode::Shared, MayUseFileMapping = MayUseFileMapping::Yes);
76
77
    static Ref<SharedBuffer> create(Vector<uint8_t>&&);
78
76
79
#if USE(FOUNDATION)
80
    RetainPtr<NSData> createNSData() const;
81
    RetainPtr<NSArray> createNSDataArray() const;
82
    static Ref<SharedBuffer> create(NSData *);
83
    void append(NSData *);
84
#endif
85
#if USE(CF)
77
#if USE(CF)
86
    RetainPtr<CFDataRef> createCFData() const;
78
    WEBCORE_EXPORT static Ref<DataSegment> create(RetainPtr<CFDataRef>&&);
87
    static Ref<SharedBuffer> create(CFDataRef);
88
    void append(CFDataRef);
89
#endif
79
#endif
90
91
#if USE(GLIB)
80
#if USE(GLIB)
92
    static Ref<SharedBuffer> create(GBytes*);
81
    WEBCORE_EXPORT static Ref<DataSegment> create(GRefPtr<GBytes>&&);
93
    GRefPtr<GBytes> createGBytes() const;
94
#endif
82
#endif
95
96
#if USE(GSTREAMER)
83
#if USE(GSTREAMER)
97
    static Ref<SharedBuffer> create(GstMappedOwnedBuffer&);
84
    WEBCORE_EXPORT static Ref<DataSegment> create(RefPtr<GstMappedOwnedBuffer>&&);
98
#endif
85
#endif
99
    // Calling data() causes all the data segments to be copied into one segment if they are not already.
86
    WEBCORE_EXPORT static Ref<DataSegment> create(FileSystem::MappedFileData&&);
100
    // Iterate the segments using begin() and end() instead.
101
    // FIXME: Audit the call sites of this function and replace them with iteration if possible.
102
    const uint8_t* data() const;
103
    const char* dataAsCharPtr() const { return reinterpret_cast<const char*>(data()); }
104
    Vector<uint8_t> copyData() const;
105
    Vector<uint8_t> read(size_t offset, size_t length) const;
106
107
    // Similar to copyData() but avoids copying and will take the data instead when it is safe (The SharedBuffer is not shared).
108
    Vector<uint8_t> extractData();
109
110
    // Creates an ArrayBuffer and copies this SharedBuffer's contents to that
111
    // ArrayBuffer without merging segmented buffers into a flat buffer.
112
    RefPtr<ArrayBuffer> tryCreateArrayBuffer() const;
113
87
114
    size_t size() const { return m_size; }
88
    struct Provider {
115
89
        Function<const uint8_t*()> data;
116
    bool isEmpty() const { return !size(); }
90
        Function<size_t()> size;
117
91
    };
118
    void append(const SharedBuffer&);
119
    void append(const uint8_t*, size_t);
120
    void append(const char* data, size_t length) { append(reinterpret_cast<const uint8_t*>(data), length); }
121
    void append(Vector<uint8_t>&&);
122
123
    void clear();
124
92
125
    Ref<SharedBuffer> copy() const;
93
    WEBCORE_EXPORT static Ref<DataSegment> create(Provider&&);
126
    void copyTo(void* destination, size_t length) const;
127
    void copyTo(void* destination, size_t offset, size_t length) const;
128
94
129
    // Data wrapped by a DataSegment should be immutable because it can be referenced by other objects.
95
#if USE(FOUNDATION)
130
    // To modify or combine the data, allocate a new DataSegment.
96
    WEBCORE_EXPORT RetainPtr<NSData> createNSData() const;
131
    class DataSegment : public ThreadSafeRefCounted<DataSegment> {
97
#endif
132
    public:
133
        WEBCORE_EXPORT const uint8_t* data() const;
134
        WEBCORE_EXPORT size_t size() const;
135
98
136
        static Ref<DataSegment> create(Vector<uint8_t>&& data)
99
    WEBCORE_EXPORT bool containsMappedFileData() const;
137
        {
138
            data.shrinkToFit();
139
            return adoptRef(*new DataSegment(WTFMove(data)));
140
        }
141
100
101
private:
102
    explicit DataSegment(Vector<uint8_t>&& data)
103
        : m_immutableData(WTFMove(data)) { }
142
#if USE(CF)
104
#if USE(CF)
143
        static Ref<DataSegment> create(RetainPtr<CFDataRef>&& data) { return adoptRef(*new DataSegment(WTFMove(data))); }
105
    explicit DataSegment(RetainPtr<CFDataRef>&& data)
106
        : m_immutableData(WTFMove(data)) { }
144
#endif
107
#endif
145
#if USE(GLIB)
108
#if USE(GLIB)
146
        static Ref<DataSegment> create(GRefPtr<GBytes>&& data) { return adoptRef(*new DataSegment(WTFMove(data))); }
109
    explicit DataSegment(GRefPtr<GBytes>&& data)
110
        : m_immutableData(WTFMove(data)) { }
147
#endif
111
#endif
148
#if USE(GSTREAMER)
112
#if USE(GSTREAMER)
149
        static Ref<DataSegment> create(RefPtr<GstMappedOwnedBuffer>&& data) { return adoptRef(*new DataSegment(WTFMove(data))); }
113
    explicit DataSegment(RefPtr<GstMappedOwnedBuffer>&& data)
114
        : m_immutableData(WTFMove(data)) { }
150
#endif
115
#endif
151
        static Ref<DataSegment> create(FileSystem::MappedFileData&& data) { return adoptRef(*new DataSegment(WTFMove(data))); }
116
    explicit DataSegment(FileSystem::MappedFileData&& data)
117
        : m_immutableData(WTFMove(data)) { }
118
    explicit DataSegment(Provider&& provider)
119
        : m_immutableData(WTFMove(provider)) { }
152
120
153
        struct Provider {
121
    std::variant<Vector<uint8_t>,
154
            Function<const uint8_t*()> data;
155
            Function<size_t()> size;
156
        };
157
158
        static Ref<DataSegment> create(Provider&& provider) { return adoptRef(*new DataSegment(WTFMove(provider))); }
159
160
#if USE(FOUNDATION)
161
        RetainPtr<NSData> createNSData() const;
162
#endif
163
164
        bool containsMappedFileData() const;
165
166
    private:
167
        DataSegment(Vector<uint8_t>&& data)
168
            : m_immutableData(WTFMove(data)) { }
169
#if USE(CF)
122
#if USE(CF)
170
        DataSegment(RetainPtr<CFDataRef>&& data)
123
        RetainPtr<CFDataRef>,
171
            : m_immutableData(WTFMove(data)) { }
172
#endif
124
#endif
173
#if USE(GLIB)
125
#if USE(GLIB)
174
        DataSegment(GRefPtr<GBytes>&& data)
126
        GRefPtr<GBytes>,
175
            : m_immutableData(WTFMove(data)) { }
176
#endif
127
#endif
177
#if USE(GSTREAMER)
128
#if USE(GSTREAMER)
178
        DataSegment(RefPtr<GstMappedOwnedBuffer>&& data)
129
        RefPtr<GstMappedOwnedBuffer>,
179
            : m_immutableData(WTFMove(data)) { }
180
#endif
130
#endif
181
        DataSegment(FileSystem::MappedFileData&& data)
131
        FileSystem::MappedFileData,
182
            : m_immutableData(WTFMove(data)) { }
132
        Provider> m_immutableData;
183
        DataSegment(Provider&& provider)
133
    friend class FragmentedSharedBuffer;
184
            : m_immutableData(WTFMove(provider)) { }
134
    friend class SharedBuffer; // For createCFData
135
};
136
137
class FragmentedSharedBuffer : public ThreadSafeRefCounted<FragmentedSharedBuffer> {
138
public:
139
    WEBCORE_EXPORT static Ref<FragmentedSharedBuffer> create();
140
    WEBCORE_EXPORT static Ref<FragmentedSharedBuffer> create(const uint8_t*, size_t);
141
    static Ref<FragmentedSharedBuffer> create(const char* data, size_t size) { return create(reinterpret_cast<const uint8_t*>(data), size); }
142
    WEBCORE_EXPORT static Ref<FragmentedSharedBuffer> create(FileSystem::MappedFileData&&);
143
    WEBCORE_EXPORT static Ref<FragmentedSharedBuffer> create(Ref<SharedBuffer>&&);
144
    WEBCORE_EXPORT static Ref<FragmentedSharedBuffer> create(Vector<uint8_t>&&);
145
    WEBCORE_EXPORT static Ref<FragmentedSharedBuffer> create(DataSegment::Provider&&);
185
146
186
        std::variant<Vector<uint8_t>,
147
#if USE(FOUNDATION)
148
    WEBCORE_EXPORT RetainPtr<NSArray> createNSDataArray() const;
149
    WEBCORE_EXPORT static Ref<FragmentedSharedBuffer> create(NSData*);
150
#endif
187
#if USE(CF)
151
#if USE(CF)
188
            RetainPtr<CFDataRef>,
152
    WEBCORE_EXPORT static Ref<FragmentedSharedBuffer> create(CFDataRef);
189
#endif
153
#endif
154
190
#if USE(GLIB)
155
#if USE(GLIB)
191
            GRefPtr<GBytes>,
156
    WEBCORE_EXPORT static Ref<FragmentedSharedBuffer> create(GBytes*);
192
#endif
157
#endif
158
193
#if USE(GSTREAMER)
159
#if USE(GSTREAMER)
194
            RefPtr<GstMappedOwnedBuffer>,
160
    WEBCORE_EXPORT static Ref<FragmentedSharedBuffer> create(GstMappedOwnedBuffer&);
195
#endif
161
#endif
196
            FileSystem::MappedFileData,
162
    WEBCORE_EXPORT Vector<uint8_t> copyData() const;
197
            Provider> m_immutableData;
163
    WEBCORE_EXPORT Vector<uint8_t> read(size_t offset, size_t length) const;
198
        friend class SharedBuffer;
164
199
    };
165
    // Similar to copyData() but avoids copying and will take the data instead when it is safe (The FragmentedSharedBuffer is not shared).
166
    Vector<uint8_t> extractData();
167
168
    // Creates an ArrayBuffer and copies this FragmentedSharedBuffer's contents to that
169
    // ArrayBuffer without merging segmented buffers into a flat buffer.
170
    WEBCORE_EXPORT RefPtr<ArrayBuffer> tryCreateArrayBuffer() const;
171
172
    size_t size() const { return m_size; }
173
    bool isEmpty() const { return !size(); }
174
    bool isContiguous() const { return m_contiguous; }
200
175
201
    static Ref<SharedBuffer> create(DataSegment::Provider&&);
176
    WEBCORE_EXPORT Ref<FragmentedSharedBuffer> copy() const;
177
    WEBCORE_EXPORT void copyTo(void* destination, size_t length) const;
178
    WEBCORE_EXPORT void copyTo(void* destination, size_t offset, size_t length) const;
202
179
203
    void forEachSegment(const Function<void(const Span<const uint8_t>&)>&) const;
180
    WEBCORE_EXPORT void forEachSegment(const Function<void(const Span<const uint8_t>&)>&) const;
204
    bool startsWith(const Span<const uint8_t>& prefix) const;
181
    WEBCORE_EXPORT bool startsWith(const Span<const uint8_t>& prefix) const;
182
183
    using DataSegment = WebCore::DataSegment; // To keep backward compatibility when using FragmentedSharedBuffer::DataSegment
205
184
206
    struct DataSegmentVectorEntry {
185
    struct DataSegmentVectorEntry {
207
        size_t beginPosition;
186
        size_t beginPosition;
Lines 210-284 public: a/Source/WebCore/platform/SharedBuffer.h_sec3
210
    using DataSegmentVector = Vector<DataSegmentVectorEntry, 1>;
189
    using DataSegmentVector = Vector<DataSegmentVectorEntry, 1>;
211
    DataSegmentVector::const_iterator begin() const { return m_segments.begin(); }
190
    DataSegmentVector::const_iterator begin() const { return m_segments.begin(); }
212
    DataSegmentVector::const_iterator end() const { return m_segments.end(); }
191
    DataSegmentVector::const_iterator end() const { return m_segments.end(); }
213
    bool hasOneSegment() const;
192
    bool hasOneSegment() const { return m_segments.size() == 1; }
214
193
215
    // begin and end take O(1) time, this takes O(log(N)) time.
194
    // begin and end take O(1) time, this takes O(log(N)) time.
216
    SharedBufferDataView getSomeData(size_t position) const;
195
    WEBCORE_EXPORT SharedBufferDataView getSomeData(size_t position) const;
217
196
218
    String toHexString() const;
197
    WEBCORE_EXPORT String toHexString() const;
219
198
220
    void hintMemoryNotNeededSoon() const;
199
    void hintMemoryNotNeededSoon() const;
221
200
222
    WTF::Persistence::Decoder decoder() const;
201
    WEBCORE_EXPORT bool operator==(const FragmentedSharedBuffer&) const;
202
    bool operator!=(const FragmentedSharedBuffer& other) const { return !operator==(other); }
223
203
224
    bool operator==(const SharedBuffer&) const;
204
    WEBCORE_EXPORT Ref<SharedBuffer> makeContiguous() const;
225
    bool operator!=(const SharedBuffer& other) const { return !operator==(other); }
226
205
227
private:
206
protected:
228
    explicit SharedBuffer() = default;
207
    friend class SharedBuffer;
229
    explicit SharedBuffer(const uint8_t*, size_t);
208
230
    explicit SharedBuffer(const char*, size_t);
209
    DataSegmentVector m_segments;
231
    explicit SharedBuffer(Vector<uint8_t>&&);
210
    bool m_contiguous { false };
232
    explicit SharedBuffer(FileSystem::MappedFileData&&);
211
233
    explicit SharedBuffer(DataSegment::Provider&&);
212
    WEBCORE_EXPORT FragmentedSharedBuffer();
213
    explicit FragmentedSharedBuffer(const uint8_t* data, size_t size) { append(data, size); }
214
    explicit FragmentedSharedBuffer(const char* data, size_t size) { append(data, size); }
215
    explicit FragmentedSharedBuffer(Vector<uint8_t>&& data) { append(WTFMove(data)); }
216
    WEBCORE_EXPORT explicit FragmentedSharedBuffer(FileSystem::MappedFileData&&);
217
    WEBCORE_EXPORT explicit FragmentedSharedBuffer(DataSegment::Provider&&);
218
    WEBCORE_EXPORT explicit FragmentedSharedBuffer(Ref<SharedBuffer>&&);
234
#if USE(CF)
219
#if USE(CF)
235
    explicit SharedBuffer(CFDataRef);
220
    WEBCORE_EXPORT explicit FragmentedSharedBuffer(CFDataRef);
236
#endif
221
#endif
237
#if USE(GLIB)
222
#if USE(GLIB)
238
    explicit SharedBuffer(GBytes*);
223
    WEBCORE_EXPORT explicit FragmentedSharedBuffer(GBytes*);
239
#endif
224
#endif
240
#if USE(GSTREAMER)
225
#if USE(GSTREAMER)
241
    explicit SharedBuffer(GstMappedOwnedBuffer&);
226
    WEBCORE_EXPORT explicit FragmentedSharedBuffer(GstMappedOwnedBuffer&);
242
#endif
227
#endif
228
    size_t m_size { 0 };
243
229
244
    void combineIntoOneSegment() const;
230
private:
231
    friend class SharedBufferBuilder;
232
    WEBCORE_EXPORT void append(const FragmentedSharedBuffer&);
233
    WEBCORE_EXPORT void append(const uint8_t*, size_t);
234
    void append(const char* data, size_t length) { append(reinterpret_cast<const uint8_t*>(data), length); }
235
    WEBCORE_EXPORT void append(Vector<uint8_t>&&);
236
#if USE(FOUNDATION)
237
    WEBCORE_EXPORT void append(NSData *);
238
#endif
239
#if USE(CF)
240
    WEBCORE_EXPORT void append(CFDataRef);
241
#endif
245
242
246
    // Combines all the segments into a Vector and returns that vector after clearing the SharedBuffer.
243
    WEBCORE_EXPORT void clear();
247
    Vector<uint8_t> takeData();
248
244
245
    // Combines all the segments into a Vector and returns that vector after clearing the FragmentedSharedBuffer.
246
    WEBCORE_EXPORT Vector<uint8_t> takeData();
249
    const DataSegmentVectorEntry* getSegmentForPosition(size_t positition) const;
247
    const DataSegmentVectorEntry* getSegmentForPosition(size_t positition) const;
250
248
251
    static RefPtr<SharedBuffer> createFromReadingFile(const String& filePath);
252
253
    size_t m_size { 0 };
254
    mutable DataSegmentVector m_segments;
255
256
#if ASSERT_ENABLED
249
#if ASSERT_ENABLED
257
    mutable bool m_hasBeenCombinedIntoOneSegment { false };
258
    bool internallyConsistent() const;
250
    bool internallyConsistent() const;
259
#endif
251
#endif
260
};
252
};
261
253
262
inline Vector<uint8_t> SharedBuffer::extractData()
254
// A SharedBuffer is a FragmentedSharedBuffer that allows to directly access its content via the data() and related methods.
255
class SharedBuffer : public FragmentedSharedBuffer {
256
public:
257
    template <typename... Args>
258
    static Ref<SharedBuffer> create(Args&&... args)
259
    {
260
        if constexpr (!sizeof...(Args))
261
            return adoptRef(*new SharedBuffer());
262
        else if constexpr (sizeof...(Args) == 1
263
            && (std::is_same_v<Args, Ref<DataSegment>> &&...))
264
            return adoptRef(*new SharedBuffer(std::forward<Args>(args)...));
265
        else {
266
            auto buffer = FragmentedSharedBuffer::create(std::forward<Args>(args)...);
267
            return adoptRef(*new SharedBuffer(WTFMove(buffer)));
268
        }
269
    }
270
271
    WEBCORE_EXPORT const uint8_t* data() const;
272
    const char* dataAsCharPtr() const { return reinterpret_cast<const char*>(data()); }
273
    WTF::Persistence::Decoder decoder() const;
274
275
    enum class MayUseFileMapping : bool { No, Yes };
276
    WEBCORE_EXPORT static RefPtr<SharedBuffer> createWithContentsOfFile(const String& filePath, FileSystem::MappedFileMode = FileSystem::MappedFileMode::Shared, MayUseFileMapping = MayUseFileMapping::Yes);
277
278
#if USE(FOUNDATION)
279
    WEBCORE_EXPORT RetainPtr<NSData> createNSData() const;
280
#endif
281
#if USE(CF)
282
    WEBCORE_EXPORT RetainPtr<CFDataRef> createCFData() const;
283
#endif
284
#if USE(GLIB)
285
    WEBCORE_EXPORT GRefPtr<GBytes> createGBytes() const;
286
#endif
287
288
private:
289
    WEBCORE_EXPORT SharedBuffer();
290
    WEBCORE_EXPORT explicit SharedBuffer(FileSystem::MappedFileData&&);
291
    WEBCORE_EXPORT explicit SharedBuffer(Ref<DataSegment>&&);
292
    WEBCORE_EXPORT explicit SharedBuffer(Ref<FragmentedSharedBuffer>&&);
293
294
    WEBCORE_EXPORT static RefPtr<SharedBuffer> createFromReadingFile(const String& filePath);
295
};
296
297
class SharedBufferBuilder {
298
    WTF_MAKE_FAST_ALLOCATED;
299
public:
300
    SharedBufferBuilder() = default;
301
    explicit SharedBufferBuilder(RefPtr<FragmentedSharedBuffer>&& buffer)
302
    {
303
        // We do not want to take a reference to the FragmentedSharedBuffer as all FragmentedSharedBuffer should be immutable
304
        // once created.
305
        if (!buffer || (buffer->hasOneRef() && !buffer->isContiguous())) {
306
            m_buffer = WTFMove(buffer);
307
            return;
308
        }
309
        append(*buffer);
310
    }
311
    explicit SharedBufferBuilder(Ref<FragmentedSharedBuffer>&& buffer)
312
    {
313
        // We do not want to take a reference to the FragmentedSharedBuffer as all FragmentedSharedBuffer should be immutable
314
        // once created.
315
        if (buffer->hasOneRef() && !buffer->isContiguous()) {
316
            m_buffer = WTFMove(buffer);
317
            return;
318
        }
319
        append(WTFMove(buffer.get()));
320
    }
321
    template <typename... Args>
322
    SharedBufferBuilder(Args&&... args)
323
        : m_buffer(FragmentedSharedBuffer::create(std::forward<Args>(args)...)) { }
324
325
    template <typename... Args>
326
    void append(Args&&... args)
327
    {
328
        ensureBuffer();
329
        m_buffer->append(std::forward<Args>(args)...);
330
    }
331
332
    explicit operator bool() const { return !isNull(); }
333
    bool isNull() const { return !m_buffer; }
334
    bool isEmpty() const { return m_buffer ? m_buffer->isEmpty() : true; }
335
336
    size_t size() const { return m_buffer ? m_buffer->size() : 0; }
337
338
    void reset() { m_buffer = nullptr; }
339
    void empty()
340
    {
341
        reset();
342
        ensureBuffer();
343
    }
344
345
    RefPtr<FragmentedSharedBuffer> get() const { return m_buffer; }
346
    Ref<FragmentedSharedBuffer> copy() const { return m_buffer ? m_buffer->copy() : FragmentedSharedBuffer::create(); }
347
    Ref<FragmentedSharedBuffer> take()
348
    {
349
        ensureBuffer();
350
        return m_buffer.releaseNonNull();
351
    }
352
353
private:
354
    void ensureBuffer()
355
    {
356
        if (!m_buffer)
357
            m_buffer = FragmentedSharedBuffer::create();
358
    }
359
    RefPtr<FragmentedSharedBuffer> m_buffer;
360
};
361
362
inline Vector<uint8_t> FragmentedSharedBuffer::extractData()
263
{
363
{
264
    if (hasOneRef())
364
    if (hasOneRef())
265
        return takeData();
365
        return takeData();
266
    return copyData();
366
    return copyData();
267
}
367
}
268
368
269
class WEBCORE_EXPORT SharedBufferDataView {
369
class SharedBufferDataView {
270
public:
370
public:
271
    SharedBufferDataView(Ref<SharedBuffer::DataSegment>&&, size_t positionWithinSegment, std::optional<size_t> newSize = std::nullopt);
371
    WEBCORE_EXPORT SharedBufferDataView(Ref<DataSegment>&&, size_t positionWithinSegment, std::optional<size_t> newSize = std::nullopt);
272
    SharedBufferDataView(const SharedBufferDataView&, size_t newSize);
372
    WEBCORE_EXPORT SharedBufferDataView(const SharedBufferDataView&, size_t newSize);
273
    size_t size() const;
373
    size_t size() const { return m_size; }
274
    const uint8_t* data() const;
374
    const uint8_t* data() const { return m_segment->data() + m_positionWithinSegment; }
275
    const char* dataAsCharPtr() const { return reinterpret_cast<const char*>(data()); }
375
    const char* dataAsCharPtr() const { return reinterpret_cast<const char*>(data()); }
276
    Ref<SharedBuffer> createSharedBuffer() const;
376
377
    WEBCORE_EXPORT Ref<SharedBuffer> createSharedBuffer() const;
277
#if USE(FOUNDATION)
378
#if USE(FOUNDATION)
278
    RetainPtr<NSData> createNSData() const;
379
    WEBCORE_EXPORT RetainPtr<NSData> createNSData() const;
279
#endif
380
#endif
280
private:
381
private:
281
    const Ref<SharedBuffer::DataSegment> m_segment;
382
    const Ref<DataSegment> m_segment;
282
    const size_t m_positionWithinSegment;
383
    const size_t m_positionWithinSegment;
283
    const size_t m_size;
384
    const size_t m_size;
284
};
385
};
- a/Source/WebCore/platform/SharedBufferChunkReader.cpp -2 / +2 lines
Lines 36-42 namespace WebCore { a/Source/WebCore/platform/SharedBufferChunkReader.cpp_sec1
36
36
37
#if ENABLE(MHTML)
37
#if ENABLE(MHTML)
38
38
39
SharedBufferChunkReader::SharedBufferChunkReader(SharedBuffer* buffer, const Vector<char>& separator)
39
SharedBufferChunkReader::SharedBufferChunkReader(FragmentedSharedBuffer* buffer, const Vector<char>& separator)
40
    : m_iteratorCurrent(buffer->begin())
40
    : m_iteratorCurrent(buffer->begin())
41
    , m_iteratorEnd(buffer->end())
41
    , m_iteratorEnd(buffer->end())
42
    , m_segment(m_iteratorCurrent != m_iteratorEnd ? m_iteratorCurrent->segment->data() : nullptr)
42
    , m_segment(m_iteratorCurrent != m_iteratorEnd ? m_iteratorCurrent->segment->data() : nullptr)
Lines 44-50 SharedBufferChunkReader::SharedBufferChunkReader(SharedBuffer* buffer, const Vec a/Source/WebCore/platform/SharedBufferChunkReader.cpp_sec2
44
{
44
{
45
}
45
}
46
46
47
SharedBufferChunkReader::SharedBufferChunkReader(SharedBuffer* buffer, const char* separator)
47
SharedBufferChunkReader::SharedBufferChunkReader(FragmentedSharedBuffer* buffer, const char* separator)
48
    : m_iteratorCurrent(buffer->begin())
48
    : m_iteratorCurrent(buffer->begin())
49
    , m_iteratorEnd(buffer->end())
49
    , m_iteratorEnd(buffer->end())
50
    , m_segment(m_iteratorCurrent != m_iteratorEnd ? m_iteratorCurrent->segment->data() : nullptr)
50
    , m_segment(m_iteratorCurrent != m_iteratorEnd ? m_iteratorCurrent->segment->data() : nullptr)
- a/Source/WebCore/platform/SharedBufferChunkReader.h -4 / +4 lines
Lines 41-48 namespace WebCore { a/Source/WebCore/platform/SharedBufferChunkReader.h_sec1
41
41
42
class WEBCORE_EXPORT SharedBufferChunkReader {
42
class WEBCORE_EXPORT SharedBufferChunkReader {
43
public:
43
public:
44
    SharedBufferChunkReader(SharedBuffer*, const Vector<char>& separator);
44
    SharedBufferChunkReader(FragmentedSharedBuffer*, const Vector<char>& separator);
45
    SharedBufferChunkReader(SharedBuffer*, const char* separator);
45
    SharedBufferChunkReader(FragmentedSharedBuffer*, const char* separator);
46
46
47
    void setSeparator(const Vector<char>&);
47
    void setSeparator(const Vector<char>&);
48
    void setSeparator(const char*);
48
    void setSeparator(const char*);
Lines 58-65 public: a/Source/WebCore/platform/SharedBufferChunkReader.h_sec2
58
    size_t peek(Vector<uint8_t>&, size_t);
58
    size_t peek(Vector<uint8_t>&, size_t);
59
59
60
private:
60
private:
61
    SharedBuffer::DataSegmentVector::const_iterator m_iteratorCurrent;
61
    FragmentedSharedBuffer::DataSegmentVector::const_iterator m_iteratorCurrent;
62
    const SharedBuffer::DataSegmentVector::const_iterator m_iteratorEnd;
62
    const FragmentedSharedBuffer::DataSegmentVector::const_iterator m_iteratorEnd;
63
    const uint8_t* m_segment { nullptr };
63
    const uint8_t* m_segment { nullptr };
64
    size_t m_segmentIndex { 0 };
64
    size_t m_segmentIndex { 0 };
65
    Vector<char> m_separator { false };
65
    Vector<char> m_separator { false };
- a/Source/WebCore/platform/StaticPasteboard.cpp -1 / +1 lines
Lines 73-79 void StaticPasteboard::writeString(const String& type, const String& value) a/Source/WebCore/platform/StaticPasteboard.cpp_sec1
73
    m_customData.writeString(type, value);
73
    m_customData.writeString(type, value);
74
}
74
}
75
75
76
void StaticPasteboard::writeData(const String& type, Ref<SharedBuffer>&& data)
76
void StaticPasteboard::writeData(const String& type, Ref<FragmentedSharedBuffer>&& data)
77
{
77
{
78
    m_nonDefaultDataTypes.add(type);
78
    m_nonDefaultDataTypes.add(type);
79
    m_customData.writeData(type, WTFMove(data));
79
    m_customData.writeData(type, WTFMove(data));
- a/Source/WebCore/platform/StaticPasteboard.h -2 / +2 lines
Lines 32-38 a/Source/WebCore/platform/StaticPasteboard.h_sec1
32
32
33
namespace WebCore {
33
namespace WebCore {
34
34
35
class SharedBuffer;
35
class FragmentedSharedBuffer;
36
36
37
class StaticPasteboard final : public Pasteboard {
37
class StaticPasteboard final : public Pasteboard {
38
public:
38
public:
Lines 52-58 public: a/Source/WebCore/platform/StaticPasteboard.h_sec2
52
    String readStringInCustomData(const String& type) final;
52
    String readStringInCustomData(const String& type) final;
53
53
54
    void writeString(const String& type, const String& data) final;
54
    void writeString(const String& type, const String& data) final;
55
    void writeData(const String& type, Ref<SharedBuffer>&& data);
55
    void writeData(const String& type, Ref<FragmentedSharedBuffer>&& data);
56
    void writeStringInCustomData(const String& type, const String& data);
56
    void writeStringInCustomData(const String& type, const String& data);
57
    void clear() final;
57
    void clear() final;
58
    void clear(const String& type) final;
58
    void clear(const String& type) final;
- a/Source/WebCore/platform/audio/NowPlayingInfo.h -2 / +2 lines
Lines 36-42 namespace WebCore { a/Source/WebCore/platform/audio/NowPlayingInfo.h_sec1
36
struct NowPlayingInfoArtwork {
36
struct NowPlayingInfoArtwork {
37
    String src;
37
    String src;
38
    String mimeType;
38
    String mimeType;
39
    RefPtr<SharedBuffer> imageData;
39
    RefPtr<FragmentedSharedBuffer> imageData;
40
40
41
    bool operator==(const NowPlayingInfoArtwork& other) const
41
    bool operator==(const NowPlayingInfoArtwork& other) const
42
    {
42
    {
Lines 67-73 template<class Decoder> inline std::optional<NowPlayingInfoArtwork> NowPlayingIn a/Source/WebCore/platform/audio/NowPlayingInfo.h_sec2
67
    if (!decoder.decode(mimeType))
67
    if (!decoder.decode(mimeType))
68
        return { };
68
        return { };
69
69
70
    RefPtr<SharedBuffer> imageData;
70
    RefPtr<FragmentedSharedBuffer> imageData;
71
    if (!decoder.decode(imageData))
71
    if (!decoder.decode(imageData))
72
        return { };
72
        return { };
73
73
- a/Source/WebCore/platform/audio/cocoa/MediaSessionManagerCocoa.mm -1 / +1 lines
Lines 341-347 void MediaSessionManagerCocoa::setNowPlayingInfo(bool setAsNowPlayingApplication a/Source/WebCore/platform/audio/cocoa/MediaSessionManagerCocoa.mm_sec1
341
        CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoElapsedTime, cfCurrentTime.get());
341
        CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoElapsedTime, cfCurrentTime.get());
342
    }
342
    }
343
    if (nowPlayingInfo.artwork && nowPlayingInfo.artwork->imageData) {
343
    if (nowPlayingInfo.artwork && nowPlayingInfo.artwork->imageData) {
344
        auto nsArtwork = nowPlayingInfo.artwork->imageData->createNSData();
344
        auto nsArtwork = nowPlayingInfo.artwork->imageData->makeContiguous()->createNSData();
345
        CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoArtworkData, nsArtwork.get());
345
        CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoArtworkData, nsArtwork.get());
346
        CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoArtworkMIMEType, nowPlayingInfo.artwork->mimeType.createCFString().get());
346
        CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoArtworkMIMEType, nowPlayingInfo.artwork->mimeType.createCFString().get());
347
        CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoArtworkIdentifier, String::number(nowPlayingInfo.artwork->src.hash()).createCFString().get());
347
        CFDictionarySetValue(info.get(), kMRMediaRemoteNowPlayingInfoArtworkIdentifier, String::number(nowPlayingInfo.artwork->src.hash()).createCFString().get());
- a/Source/WebCore/platform/cf/SharedBufferCF.cpp -12 / +7 lines
Lines 33-39 a/Source/WebCore/platform/cf/SharedBufferCF.cpp_sec1
33
33
34
namespace WebCore {
34
namespace WebCore {
35
35
36
SharedBuffer::SharedBuffer(CFDataRef data)
36
FragmentedSharedBuffer::FragmentedSharedBuffer(CFDataRef data)
37
{
37
{
38
    append(data);
38
    append(data);
39
}
39
}
Lines 43-66 SharedBuffer::SharedBuffer(CFDataRef data) a/Source/WebCore/platform/cf/SharedBufferCF.cpp_sec2
43
#if !USE(FOUNDATION)
43
#if !USE(FOUNDATION)
44
RetainPtr<CFDataRef> SharedBuffer::createCFData() const
44
RetainPtr<CFDataRef> SharedBuffer::createCFData() const
45
{
45
{
46
    if (m_segments.size() == 1) {
46
    if (hasOneSegment()) {
47
        if (auto* data = std::get_if<RetainPtr<CFDataRef>>(&m_segments[0].segment->m_immutableData))
47
        if (auto* data = std::get_if<RetainPtr<CFDataRef>>(&m_segments[0].segment->m_immutableData))
48
            return *data;
48
            return *data;
49
    }
49
    }
50
    auto cfData = adoptCF(CFDataCreateMutable(nullptr, size()));
50
    return adoptCF(CFDataCreate(nullptr, data(), size()));
51
    forEachSegment([&](auto& segment) {
52
        CFDataAppendBytes(cfData.get(), segment.data(), segment.size());
53
    });
54
    return cfData;
55
}
51
}
56
#endif
52
#endif
57
53
58
Ref<SharedBuffer> SharedBuffer::create(CFDataRef data)
54
Ref<FragmentedSharedBuffer> FragmentedSharedBuffer::create(CFDataRef data)
59
{
55
{
60
    return adoptRef(*new SharedBuffer(data));
56
    return adoptRef(*new FragmentedSharedBuffer(data));
61
}
57
}
62
58
63
void SharedBuffer::hintMemoryNotNeededSoon() const
59
void FragmentedSharedBuffer::hintMemoryNotNeededSoon() const
64
{
60
{
65
    for (const auto& entry : m_segments) {
61
    for (const auto& entry : m_segments) {
66
        if (entry.segment->hasOneRef()) {
62
        if (entry.segment->hasOneRef()) {
Lines 70-78 void SharedBuffer::hintMemoryNotNeededSoon() const a/Source/WebCore/platform/cf/SharedBufferCF.cpp_sec3
70
    }
66
    }
71
}
67
}
72
68
73
void SharedBuffer::append(CFDataRef data)
69
void FragmentedSharedBuffer::append(CFDataRef data)
74
{
70
{
75
    ASSERT(!m_hasBeenCombinedIntoOneSegment);
76
    if (data) {
71
    if (data) {
77
        m_segments.append({m_size, DataSegment::create(data)});
72
        m_segments.append({m_size, DataSegment::create(data)});
78
        m_size += CFDataGetLength(data);
73
        m_size += CFDataGetLength(data);
- a/Source/WebCore/platform/cocoa/NetworkExtensionContentFilter.h -1 / +1 lines
Lines 51-57 public: a/Source/WebCore/platform/cocoa/NetworkExtensionContentFilter.h_sec1
51
    void responseReceived(const ResourceResponse&) override;
51
    void responseReceived(const ResourceResponse&) override;
52
    void addData(const uint8_t* data, int length) override;
52
    void addData(const uint8_t* data, int length) override;
53
    void finishedAddingData() override;
53
    void finishedAddingData() override;
54
    Ref<SharedBuffer> replacementData() const override;
54
    Ref<FragmentedSharedBuffer> replacementData() const override;
55
    ContentFilterUnblockHandler unblockHandler() const override;
55
    ContentFilterUnblockHandler unblockHandler() const override;
56
56
57
    WEBCORE_EXPORT static bool isRequired();
57
    WEBCORE_EXPORT static bool isRequired();
- a/Source/WebCore/platform/cocoa/NetworkExtensionContentFilter.mm -1 / +1 lines
Lines 175-181 void NetworkExtensionContentFilter::finishedAddingData() a/Source/WebCore/platform/cocoa/NetworkExtensionContentFilter.mm_sec1
175
    semaphore.wait();
175
    semaphore.wait();
176
}
176
}
177
177
178
Ref<SharedBuffer> NetworkExtensionContentFilter::replacementData() const
178
Ref<FragmentedSharedBuffer> NetworkExtensionContentFilter::replacementData() const
179
{
179
{
180
    ASSERT(didBlockData());
180
    ASSERT(didBlockData());
181
    return SharedBuffer::create(m_replacementData.get());
181
    return SharedBuffer::create(m_replacementData.get());
- a/Source/WebCore/platform/cocoa/ParentalControlsContentFilter.h -1 / +1 lines
Lines 45-51 public: a/Source/WebCore/platform/cocoa/ParentalControlsContentFilter.h_sec1
45
    void responseReceived(const ResourceResponse&) override;
45
    void responseReceived(const ResourceResponse&) override;
46
    void addData(const uint8_t* data, int length) override;
46
    void addData(const uint8_t* data, int length) override;
47
    void finishedAddingData() override;
47
    void finishedAddingData() override;
48
    Ref<SharedBuffer> replacementData() const override;
48
    Ref<FragmentedSharedBuffer> replacementData() const override;
49
#if ENABLE(CONTENT_FILTERING)
49
#if ENABLE(CONTENT_FILTERING)
50
    ContentFilterUnblockHandler unblockHandler() const override;
50
    ContentFilterUnblockHandler unblockHandler() const override;
51
#endif
51
#endif
- a/Source/WebCore/platform/cocoa/ParentalControlsContentFilter.mm -1 / +1 lines
Lines 109-115 void ParentalControlsContentFilter::finishedAddingData() a/Source/WebCore/platform/cocoa/ParentalControlsContentFilter.mm_sec1
109
    updateFilterState();
109
    updateFilterState();
110
}
110
}
111
111
112
Ref<SharedBuffer> ParentalControlsContentFilter::replacementData() const
112
Ref<FragmentedSharedBuffer> ParentalControlsContentFilter::replacementData() const
113
{
113
{
114
    ASSERT(didBlockData());
114
    ASSERT(didBlockData());
115
    return SharedBuffer::create(m_replacementData.get());
115
    return SharedBuffer::create(m_replacementData.get());
- a/Source/WebCore/platform/cocoa/PasteboardCocoa.mm -3 / +3 lines
Lines 47-53 static NSBitmapImageFileType bitmapPNGFileType() a/Source/WebCore/platform/cocoa/PasteboardCocoa.mm_sec1
47
}
47
}
48
#endif // PLATFORM(MAC)
48
#endif // PLATFORM(MAC)
49
49
50
// Making this non-inline so that WebKit 2's decoding doesn't have to include SharedBuffer.h.
50
// Making this non-inline so that WebKit 2's decoding doesn't have to include FragmentedSharedBuffer.h.
51
PasteboardWebContent::PasteboardWebContent() = default;
51
PasteboardWebContent::PasteboardWebContent() = default;
52
PasteboardWebContent::~PasteboardWebContent() = default;
52
PasteboardWebContent::~PasteboardWebContent() = default;
53
53
Lines 211-219 Vector<String> Pasteboard::typesForLegacyUnsafeBindings() a/Source/WebCore/platform/cocoa/PasteboardCocoa.mm_sec2
211
}
211
}
212
212
213
#if PLATFORM(MAC)
213
#if PLATFORM(MAC)
214
static Ref<SharedBuffer> convertTIFFToPNG(SharedBuffer& tiffBuffer)
214
static Ref<SharedBuffer> convertTIFFToPNG(FragmentedSharedBuffer& tiffBuffer)
215
{
215
{
216
    auto image = adoptNS([[NSBitmapImageRep alloc] initWithData: tiffBuffer.createNSData().get()]);
216
    auto image = adoptNS([[NSBitmapImageRep alloc] initWithData: tiffBuffer.makeContiguous()->createNSData().get()]);
217
    NSData *pngData = [image representationUsingType:bitmapPNGFileType() properties:@{ }];
217
    NSData *pngData = [image representationUsingType:bitmapPNGFileType() properties:@{ }];
218
    return SharedBuffer::create(pngData);
218
    return SharedBuffer::create(pngData);
219
}
219
}
- a/Source/WebCore/platform/cocoa/SharedBufferCocoa.mm -10 / +9 lines
Lines 35-45 a/Source/WebCore/platform/cocoa/SharedBufferCocoa.mm_sec1
35
#import <wtf/cocoa/VectorCocoa.h>
35
#import <wtf/cocoa/VectorCocoa.h>
36
36
37
@interface WebCoreSharedBufferData : NSData
37
@interface WebCoreSharedBufferData : NSData
38
- (instancetype)initWithDataSegment:(const WebCore::SharedBuffer::DataSegment&)dataSegment position:(NSUInteger)position size:(NSUInteger)size;
38
- (instancetype)initWithDataSegment:(const WebCore::DataSegment&)dataSegment position:(NSUInteger)position size:(NSUInteger)size;
39
@end
39
@end
40
40
41
@implementation WebCoreSharedBufferData {
41
@implementation WebCoreSharedBufferData {
42
    RefPtr<const WebCore::SharedBuffer::DataSegment> _dataSegment;
42
    RefPtr<const WebCore::DataSegment> _dataSegment;
43
    NSUInteger _position;
43
    NSUInteger _position;
44
    NSUInteger _size;
44
    NSUInteger _size;
45
}
45
}
Lines 61-67 - (void)dealloc a/Source/WebCore/platform/cocoa/SharedBufferCocoa.mm_sec2
61
    [super dealloc];
61
    [super dealloc];
62
}
62
}
63
63
64
- (instancetype)initWithDataSegment:(const WebCore::SharedBuffer::DataSegment&)dataSegment position:(NSUInteger)position size:(NSUInteger)size
64
- (instancetype)initWithDataSegment:(const WebCore::DataSegment&)dataSegment position:(NSUInteger)position size:(NSUInteger)size
65
{
65
{
66
    if (!(self = [super init]))
66
    if (!(self = [super init]))
67
        return nil;
67
        return nil;
Lines 88-100 @end a/Source/WebCore/platform/cocoa/SharedBufferCocoa.mm_sec3
88
88
89
namespace WebCore {
89
namespace WebCore {
90
90
91
Ref<SharedBuffer> SharedBuffer::create(NSData *data)
91
Ref<FragmentedSharedBuffer> FragmentedSharedBuffer::create(NSData *data)
92
{
92
{
93
    return adoptRef(*new SharedBuffer(bridge_cast(data)));
93
    return adoptRef(*new FragmentedSharedBuffer(bridge_cast(data)));
94
}
94
}
95
95
96
void SharedBuffer::append(NSData *data)
96
void FragmentedSharedBuffer::append(NSData *data)
97
{
97
{
98
    ASSERT(!m_contiguous);
98
    return append(bridge_cast(data));
99
    return append(bridge_cast(data));
99
}
100
}
100
101
Lines 105-114 RetainPtr<NSData> SharedBuffer::createNSData() const a/Source/WebCore/platform/cocoa/SharedBufferCocoa.mm_sec4
105
106
106
RetainPtr<CFDataRef> SharedBuffer::createCFData() const
107
RetainPtr<CFDataRef> SharedBuffer::createCFData() const
107
{
108
{
108
    combineIntoOneSegment();
109
    if (!m_segments.size())
109
    if (!m_segments.size())
110
        return adoptCF(CFDataCreate(nullptr, nullptr, 0));
110
        return adoptCF(CFDataCreate(nullptr, nullptr, 0));
111
    ASSERT(m_segments.size() == 1);
112
    return bridge_cast(m_segments[0].segment->createNSData());
111
    return bridge_cast(m_segments[0].segment->createNSData());
113
}
112
}
114
113
Lines 119-132 RefPtr<SharedBuffer> SharedBuffer::createFromReadingFile(const String& filePath) a/Source/WebCore/platform/cocoa/SharedBufferCocoa.mm_sec5
119
    return nullptr;
118
    return nullptr;
120
}
119
}
121
120
122
RetainPtr<NSArray> SharedBuffer::createNSDataArray() const
121
RetainPtr<NSArray> FragmentedSharedBuffer::createNSDataArray() const
123
{
122
{
124
    return createNSArray(m_segments, [] (auto& segment) {
123
    return createNSArray(m_segments, [] (auto& segment) {
125
        return segment.segment->createNSData();
124
        return segment.segment->createNSData();
126
    });
125
    });
127
}
126
}
128
127
129
RetainPtr<NSData> SharedBuffer::DataSegment::createNSData() const
128
RetainPtr<NSData> DataSegment::createNSData() const
130
{
129
{
131
    return adoptNS([[WebCoreSharedBufferData alloc] initWithDataSegment:*this position:0 size:size()]);
130
    return adoptNS([[WebCoreSharedBufferData alloc] initWithDataSegment:*this position:0 size:size()]);
132
}
131
}
- a/Source/WebCore/platform/encryptedmedia/CDMInstance.h -3 / +3 lines
Lines 46-52 class Logger; a/Source/WebCore/platform/encryptedmedia/CDMInstance.h_sec1
46
46
47
namespace WebCore {
47
namespace WebCore {
48
48
49
class SharedBuffer;
49
class FragmentedSharedBuffer;
50
class CDMInstanceSession;
50
class CDMInstanceSession;
51
struct CDMKeySystemConfiguration;
51
struct CDMKeySystemConfiguration;
52
52
Lines 54-60 class CDMInstanceClient : public CanMakeWeakPtr<CDMInstanceClient> { a/Source/WebCore/platform/encryptedmedia/CDMInstance.h_sec2
54
public:
54
public:
55
    virtual ~CDMInstanceClient() = default;
55
    virtual ~CDMInstanceClient() = default;
56
56
57
    virtual void unrequestedInitializationDataReceived(const String&, Ref<SharedBuffer>&&) = 0;
57
    virtual void unrequestedInitializationDataReceived(const String&, Ref<FragmentedSharedBuffer>&&) = 0;
58
};
58
};
59
59
60
// JavaScript's handle to a CDMInstance, must be used from the
60
// JavaScript's handle to a CDMInstance, must be used from the
Lines 98-104 public: a/Source/WebCore/platform/encryptedmedia/CDMInstance.h_sec3
98
    };
98
    };
99
99
100
    virtual void initializeWithConfiguration(const CDMKeySystemConfiguration&, AllowDistinctiveIdentifiers, AllowPersistentState, SuccessCallback&&) = 0;
100
    virtual void initializeWithConfiguration(const CDMKeySystemConfiguration&, AllowDistinctiveIdentifiers, AllowPersistentState, SuccessCallback&&) = 0;
101
    virtual void setServerCertificate(Ref<SharedBuffer>&&, SuccessCallback&&) = 0;
101
    virtual void setServerCertificate(Ref<FragmentedSharedBuffer>&&, SuccessCallback&&) = 0;
102
    virtual void setStorageDirectory(const String&) = 0;
102
    virtual void setStorageDirectory(const String&) = 0;
103
    virtual const String& keySystem() const = 0;
103
    virtual const String& keySystem() const = 0;
104
    virtual RefPtr<CDMInstanceSession> createSession() = 0;
104
    virtual RefPtr<CDMInstanceSession> createSession() = 0;
- a/Source/WebCore/platform/encryptedmedia/CDMInstanceSession.h -8 / +8 lines
Lines 43-58 class Logger; a/Source/WebCore/platform/encryptedmedia/CDMInstanceSession.h_sec1
43
43
44
namespace WebCore {
44
namespace WebCore {
45
45
46
class SharedBuffer;
46
class FragmentedSharedBuffer;
47
47
48
class CDMInstanceSessionClient : public CanMakeWeakPtr<CDMInstanceSessionClient> {
48
class CDMInstanceSessionClient : public CanMakeWeakPtr<CDMInstanceSessionClient> {
49
public:
49
public:
50
    virtual ~CDMInstanceSessionClient() = default;
50
    virtual ~CDMInstanceSessionClient() = default;
51
51
52
    using KeyStatus = CDMKeyStatus;
52
    using KeyStatus = CDMKeyStatus;
53
    using KeyStatusVector = Vector<std::pair<Ref<SharedBuffer>, KeyStatus>>;
53
    using KeyStatusVector = Vector<std::pair<Ref<FragmentedSharedBuffer>, KeyStatus>>;
54
    virtual void updateKeyStatuses(KeyStatusVector&&) = 0;
54
    virtual void updateKeyStatuses(KeyStatusVector&&) = 0;
55
    virtual void sendMessage(CDMMessageType, Ref<SharedBuffer>&& message) = 0;
55
    virtual void sendMessage(CDMMessageType, Ref<FragmentedSharedBuffer>&& message) = 0;
56
    virtual void sessionIdChanged(const String&) = 0;
56
    virtual void sessionIdChanged(const String&) = 0;
57
    using PlatformDisplayID = uint32_t;
57
    using PlatformDisplayID = uint32_t;
58
    virtual PlatformDisplayID displayID() = 0;
58
    virtual PlatformDisplayID displayID() = 0;
Lines 78-90 public: a/Source/WebCore/platform/encryptedmedia/CDMInstanceSession.h_sec2
78
        Succeeded,
78
        Succeeded,
79
    };
79
    };
80
80
81
    using LicenseCallback = CompletionHandler<void(Ref<SharedBuffer>&& message, const String& sessionId, bool needsIndividualization, SuccessValue succeeded)>;
81
    using LicenseCallback = CompletionHandler<void(Ref<FragmentedSharedBuffer>&& message, const String& sessionId, bool needsIndividualization, SuccessValue succeeded)>;
82
    virtual void requestLicense(LicenseType, const AtomString& initDataType, Ref<SharedBuffer>&& initData, LicenseCallback&&) = 0;
82
    virtual void requestLicense(LicenseType, const AtomString& initDataType, Ref<FragmentedSharedBuffer>&& initData, LicenseCallback&&) = 0;
83
83
84
    using KeyStatusVector = CDMInstanceSessionClient::KeyStatusVector;
84
    using KeyStatusVector = CDMInstanceSessionClient::KeyStatusVector;
85
    using Message = std::pair<MessageType, Ref<SharedBuffer>>;
85
    using Message = std::pair<MessageType, Ref<FragmentedSharedBuffer>>;
86
    using LicenseUpdateCallback = CompletionHandler<void(bool sessionWasClosed, std::optional<KeyStatusVector>&& changedKeys, std::optional<double>&& changedExpiration, std::optional<Message>&& message, SuccessValue succeeded)>;
86
    using LicenseUpdateCallback = CompletionHandler<void(bool sessionWasClosed, std::optional<KeyStatusVector>&& changedKeys, std::optional<double>&& changedExpiration, std::optional<Message>&& message, SuccessValue succeeded)>;
87
    virtual void updateLicense(const String& sessionId, LicenseType, Ref<SharedBuffer>&& response, LicenseUpdateCallback&&) = 0;
87
    virtual void updateLicense(const String& sessionId, LicenseType, Ref<FragmentedSharedBuffer>&& response, LicenseUpdateCallback&&) = 0;
88
88
89
    enum class SessionLoadFailure : uint8_t {
89
    enum class SessionLoadFailure : uint8_t {
90
        None,
90
        None,
Lines 100-106 public: a/Source/WebCore/platform/encryptedmedia/CDMInstanceSession.h_sec3
100
    using CloseSessionCallback = CompletionHandler<void()>;
100
    using CloseSessionCallback = CompletionHandler<void()>;
101
    virtual void closeSession(const String& sessionId, CloseSessionCallback&&) = 0;
101
    virtual void closeSession(const String& sessionId, CloseSessionCallback&&) = 0;
102
102
103
    using RemoveSessionDataCallback = CompletionHandler<void(KeyStatusVector&&, std::optional<Ref<SharedBuffer>>&&, SuccessValue)>;
103
    using RemoveSessionDataCallback = CompletionHandler<void(KeyStatusVector&&, std::optional<Ref<FragmentedSharedBuffer>>&&, SuccessValue)>;
104
    virtual void removeSessionData(const String& sessionId, LicenseType, RemoveSessionDataCallback&&) = 0;
104
    virtual void removeSessionData(const String& sessionId, LicenseType, RemoveSessionDataCallback&&) = 0;
105
105
106
    virtual void storeRecordOfKeyUsage(const String& sessionId) = 0;
106
    virtual void storeRecordOfKeyUsage(const String& sessionId) = 0;
- a/Source/WebCore/platform/encryptedmedia/CDMPrivate.h -2 / +2 lines
Lines 73-80 public: a/Source/WebCore/platform/encryptedmedia/CDMPrivate.h_sec1
73
    virtual void loadAndInitialize() = 0;
73
    virtual void loadAndInitialize() = 0;
74
    virtual bool supportsServerCertificates() const = 0;
74
    virtual bool supportsServerCertificates() const = 0;
75
    virtual bool supportsSessions() const = 0;
75
    virtual bool supportsSessions() const = 0;
76
    virtual bool supportsInitData(const AtomString&, const SharedBuffer&) const = 0;
76
    virtual bool supportsInitData(const AtomString&, const FragmentedSharedBuffer&) const = 0;
77
    virtual RefPtr<SharedBuffer> sanitizeResponse(const SharedBuffer&) const = 0;
77
    virtual RefPtr<FragmentedSharedBuffer> sanitizeResponse(const FragmentedSharedBuffer&) const = 0;
78
    virtual std::optional<String> sanitizeSessionId(const String&) const = 0;
78
    virtual std::optional<String> sanitizeSessionId(const String&) const = 0;
79
79
80
protected:
80
protected:
- a/Source/WebCore/platform/encryptedmedia/CDMProxy.cpp -1 / +1 lines
Lines 227-233 CDMInstanceSession::KeyStatusVector KeyStore::convertToJSKeyStatusVector() const a/Source/WebCore/platform/encryptedmedia/CDMProxy.cpp_sec1
227
    CDMInstanceSession::KeyStatusVector keyStatusVector;
227
    CDMInstanceSession::KeyStatusVector keyStatusVector;
228
    keyStatusVector.reserveInitialCapacity(numKeys());
228
    keyStatusVector.reserveInitialCapacity(numKeys());
229
    for (const auto& key : m_keys)
229
    for (const auto& key : m_keys)
230
        keyStatusVector.uncheckedAppend(std::pair<Ref<SharedBuffer>, CDMInstanceSession::KeyStatus> { key->idAsSharedBuffer(), key->status() });
230
        keyStatusVector.uncheckedAppend(std::pair<Ref<FragmentedSharedBuffer>, CDMInstanceSession::KeyStatus> { key->idAsSharedBuffer(), key->status() });
231
    return keyStatusVector;
231
    return keyStatusVector;
232
}
232
}
233
233
- a/Source/WebCore/platform/encryptedmedia/CDMProxy.h -1 / +1 lines
Lines 61-67 public: a/Source/WebCore/platform/encryptedmedia/CDMProxy.h_sec1
61
    {
61
    {
62
        return adoptRef(*new KeyHandle(status, WTFMove(keyID), WTFMove(keyHandleValue)));
62
        return adoptRef(*new KeyHandle(status, WTFMove(keyID), WTFMove(keyHandleValue)));
63
    }
63
    }
64
    Ref<SharedBuffer> idAsSharedBuffer() const { return SharedBuffer::create(m_id.data(), m_id.size()); }
64
    Ref<FragmentedSharedBuffer> idAsSharedBuffer() const { return SharedBuffer::create(m_id.data(), m_id.size()); }
65
65
66
    bool takeValueIfDifferent(KeyHandleValueVariant&&);
66
    bool takeValueIfDifferent(KeyHandleValueVariant&&);
67
67
- a/Source/WebCore/platform/encryptedmedia/CDMUtilities.cpp -2 / +2 lines
Lines 38-44 namespace WebCore { a/Source/WebCore/platform/encryptedmedia/CDMUtilities.cpp_sec1
38
38
39
namespace CDMUtilities {
39
namespace CDMUtilities {
40
40
41
RefPtr<JSON::Object> parseJSONObject(const SharedBuffer& buffer)
41
RefPtr<JSON::Object> parseJSONObject(const FragmentedSharedBuffer& buffer)
42
{
42
{
43
    // Fail on large buffers whose size doesn't fit into a 32-bit unsigned integer.
43
    // Fail on large buffers whose size doesn't fit into a 32-bit unsigned integer.
44
    size_t size = buffer.size();
44
    size_t size = buffer.size();
Lines 46-52 RefPtr<JSON::Object> parseJSONObject(const SharedBuffer& buffer) a/Source/WebCore/platform/encryptedmedia/CDMUtilities.cpp_sec2
46
        return nullptr;
46
        return nullptr;
47
47
48
    // Parse the buffer contents as JSON, returning the root object (if any).
48
    // Parse the buffer contents as JSON, returning the root object (if any).
49
    String json { buffer.data(), static_cast<unsigned>(size) };
49
    String json { buffer.makeContiguous()->data(), static_cast<unsigned>(size) };
50
50
51
    auto value = JSON::Value::parseJSON(json);
51
    auto value = JSON::Value::parseJSON(json);
52
    if (!value)
52
    if (!value)
- a/Source/WebCore/platform/encryptedmedia/CDMUtilities.h -2 / +2 lines
Lines 35-45 a/Source/WebCore/platform/encryptedmedia/CDMUtilities.h_sec1
35
35
36
namespace WebCore {
36
namespace WebCore {
37
37
38
class SharedBuffer;
38
class FragmentedSharedBuffer;
39
39
40
namespace CDMUtilities {
40
namespace CDMUtilities {
41
41
42
RefPtr<JSON::Object> parseJSONObject(const SharedBuffer&);
42
RefPtr<JSON::Object> parseJSONObject(const FragmentedSharedBuffer&);
43
43
44
};
44
};
45
45
- a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp -24 / +26 lines
Lines 130-136 static bool parseLicenseReleaseAcknowledgementFormat(const JSON::Object& root) a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp_sec1
130
// ];
130
// ];
131
131
132
// This function extracts the KeyIds count and the location of the first KeyId in initData buffer.
132
// This function extracts the KeyIds count and the location of the first KeyId in initData buffer.
133
static std::pair<unsigned, unsigned> extractKeyidsLocationFromCencInitData(const SharedBuffer& initData)
133
static std::pair<unsigned, unsigned> extractKeyidsLocationFromCencInitData(const FragmentedSharedBuffer& initData)
134
{
134
{
135
    std::pair<unsigned, unsigned> keyIdsMap(0, 0);
135
    std::pair<unsigned, unsigned> keyIdsMap(0, 0);
136
136
Lines 138-144 static std::pair<unsigned, unsigned> extractKeyidsLocationFromCencInitData(const a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp_sec2
138
    if (initData.isEmpty() || initData.size() > std::numeric_limits<unsigned>::max())
138
    if (initData.isEmpty() || initData.size() > std::numeric_limits<unsigned>::max())
139
        return keyIdsMap;
139
        return keyIdsMap;
140
140
141
    auto* data = initData.data();
141
    auto contiguousInitData = initData.makeContiguous();
142
    auto* data = contiguousInitData->data();
142
    unsigned initDataSize = initData.size();
143
    unsigned initDataSize = initData.size();
143
    unsigned index = 0;
144
    unsigned index = 0;
144
    unsigned psshSize = 0;
145
    unsigned psshSize = 0;
Lines 188-202 static std::pair<unsigned, unsigned> extractKeyidsLocationFromCencInitData(const a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp_sec3
188
}
189
}
189
190
190
// This function checks if the initData sharedBuffer is a valid CENC initData.
191
// This function checks if the initData sharedBuffer is a valid CENC initData.
191
static bool isCencInitData(const SharedBuffer& initData)
192
static bool isCencInitData(const FragmentedSharedBuffer& initData)
192
{
193
{
193
    std::pair<unsigned, unsigned> keyIdsMap = extractKeyidsLocationFromCencInitData(initData);
194
    std::pair<unsigned, unsigned> keyIdsMap = extractKeyidsLocationFromCencInitData(initData);
194
    return ((keyIdsMap.first) && (keyIdsMap.second));
195
    return ((keyIdsMap.first) && (keyIdsMap.second));
195
}
196
}
196
197
197
static Ref<SharedBuffer> extractKeyidsFromCencInitData(const SharedBuffer& initData)
198
static Ref<FragmentedSharedBuffer> extractKeyidsFromCencInitData(const FragmentedSharedBuffer& initData)
198
{
199
{
199
    Ref<SharedBuffer> keyIds = SharedBuffer::create();
200
    SharedBufferBuilder keyIds;
200
201
201
    std::pair<unsigned, unsigned> keyIdsMap = extractKeyidsLocationFromCencInitData(initData);
202
    std::pair<unsigned, unsigned> keyIdsMap = extractKeyidsLocationFromCencInitData(initData);
202
    unsigned keyIdCount = keyIdsMap.first;
203
    unsigned keyIdCount = keyIdsMap.first;
Lines 204-212 static Ref<SharedBuffer> extractKeyidsFromCencInitData(const SharedBuffer& initD a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp_sec4
204
205
205
    // Check if initData is a valid CENC initData.
206
    // Check if initData is a valid CENC initData.
206
    if (!keyIdCount || !index)
207
    if (!keyIdCount || !index)
207
        return keyIds;
208
        return keyIds.take();
208
209
209
    auto* data = initData.data();
210
    auto contiguousInitData = initData.makeContiguous();
211
    auto* data = contiguousInitData->data();
210
212
211
    auto object = JSON::Object::create();
213
    auto object = JSON::Object::create();
212
    auto keyIdsArray = JSON::Array::create();
214
    auto keyIdsArray = JSON::Array::create();
Lines 224-240 static Ref<SharedBuffer> extractKeyidsFromCencInitData(const SharedBuffer& initD a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp_sec5
224
226
225
    object->setArray("kids", WTFMove(keyIdsArray));
227
    object->setArray("kids", WTFMove(keyIdsArray));
226
    CString jsonData = object->toJSONString().utf8();
228
    CString jsonData = object->toJSONString().utf8();
227
    keyIds->append(jsonData.data(), jsonData.length());
229
    keyIds.append(jsonData.data(), jsonData.length());
228
    return keyIds;
230
    return keyIds.take();
229
}
231
}
230
232
231
static Ref<SharedBuffer> extractKeyIdFromWebMInitData(const SharedBuffer& initData)
233
static Ref<FragmentedSharedBuffer> extractKeyIdFromWebMInitData(const FragmentedSharedBuffer& initData)
232
{
234
{
233
    Ref<SharedBuffer> keyIds = SharedBuffer::create();
235
    SharedBufferBuilder keyIds;
234
236
235
    // Check if initData is a valid WebM initData.
237
    // Check if initData is a valid WebM initData.
236
    if (initData.isEmpty() || initData.size() > std::numeric_limits<unsigned>::max())
238
    if (initData.isEmpty() || initData.size() > std::numeric_limits<unsigned>::max())
237
        return keyIds;
239
        return keyIds.take();
238
240
239
    auto object = JSON::Object::create();
241
    auto object = JSON::Object::create();
240
    auto keyIdsArray = JSON::Array::create();
242
    auto keyIdsArray = JSON::Array::create();
Lines 245-256 static Ref<SharedBuffer> extractKeyIdFromWebMInitData(const SharedBuffer& initDa a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp_sec6
245
    // The format is a JSON object containing the following members:
247
    // The format is a JSON object containing the following members:
246
    // "kids"
248
    // "kids"
247
    // An array of key IDs. Each element of the array is the base64url encoding of the octet sequence containing the key ID value.
249
    // An array of key IDs. Each element of the array is the base64url encoding of the octet sequence containing the key ID value.
248
    keyIdsArray->pushString(base64URLEncodeToString(initData.data(), initData.size()));
250
    keyIdsArray->pushString(base64URLEncodeToString(initData.makeContiguous()->data(), initData.size()));
249
251
250
    object->setArray("kids", WTFMove(keyIdsArray));
252
    object->setArray("kids", WTFMove(keyIdsArray));
251
    CString jsonData = object->toJSONString().utf8();
253
    CString jsonData = object->toJSONString().utf8();
252
    keyIds->append(jsonData.data(), jsonData.length());
254
    keyIds.append(jsonData.data(), jsonData.length());
253
    return keyIds;
255
    return keyIds.take();
254
}
256
}
255
257
256
CDMFactoryClearKey& CDMFactoryClearKey::singleton()
258
CDMFactoryClearKey& CDMFactoryClearKey::singleton()
Lines 388-394 bool CDMPrivateClearKey::supportsSessions() const a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp_sec7
388
    return true;
390
    return true;
389
}
391
}
390
392
391
bool CDMPrivateClearKey::supportsInitData(const AtomString& initDataType, const SharedBuffer& initData) const
393
bool CDMPrivateClearKey::supportsInitData(const AtomString& initDataType, const FragmentedSharedBuffer& initData) const
392
{
394
{
393
    // Validate the initData buffer as an JSON object in keyids case.
395
    // Validate the initData buffer as an JSON object in keyids case.
394
    if (equalLettersIgnoringASCIICase(initDataType, "keyids") && CDMUtilities::parseJSONObject(initData))
396
    if (equalLettersIgnoringASCIICase(initDataType, "keyids") && CDMUtilities::parseJSONObject(initData))
Lines 405-411 bool CDMPrivateClearKey::supportsInitData(const AtomString& initDataType, const a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp_sec8
405
    return false;
407
    return false;
406
}
408
}
407
409
408
RefPtr<SharedBuffer> CDMPrivateClearKey::sanitizeResponse(const SharedBuffer& response) const
410
RefPtr<FragmentedSharedBuffer> CDMPrivateClearKey::sanitizeResponse(const FragmentedSharedBuffer& response) const
409
{
411
{
410
    // Validate the response buffer as an JSON object.
412
    // Validate the response buffer as an JSON object.
411
    if (!CDMUtilities::parseJSONObject(response))
413
    if (!CDMUtilities::parseJSONObject(response))
Lines 431-437 void CDMInstanceClearKey::initializeWithConfiguration(const CDMKeySystemConfigur a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp_sec9
431
    callback(succeeded);
433
    callback(succeeded);
432
}
434
}
433
435
434
void CDMInstanceClearKey::setServerCertificate(Ref<SharedBuffer>&&, SuccessCallback&& callback)
436
void CDMInstanceClearKey::setServerCertificate(Ref<FragmentedSharedBuffer>&&, SuccessCallback&& callback)
435
{
437
{
436
    // Reject setting any server certificate.
438
    // Reject setting any server certificate.
437
    callback(Failed);
439
    callback(Failed);
Lines 453-459 RefPtr<CDMInstanceSession> CDMInstanceClearKey::createSession() a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp_sec10
453
    return adoptRef(new CDMInstanceSessionClearKey(*this));
455
    return adoptRef(new CDMInstanceSessionClearKey(*this));
454
}
456
}
455
457
456
void CDMInstanceSessionClearKey::requestLicense(LicenseType, const AtomString& initDataType, Ref<SharedBuffer>&& initData, LicenseCallback&& callback)
458
void CDMInstanceSessionClearKey::requestLicense(LicenseType, const AtomString& initDataType, Ref<FragmentedSharedBuffer>&& initData, LicenseCallback&& callback)
457
{
459
{
458
    static uint32_t s_sessionIdValue = 0;
460
    static uint32_t s_sessionIdValue = 0;
459
    ++s_sessionIdValue;
461
    ++s_sessionIdValue;
Lines 475-481 void CDMInstanceSessionClearKey::requestLicense(LicenseType, const AtomString& i a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp_sec11
475
        });
477
        });
476
}
478
}
477
479
478
void CDMInstanceSessionClearKey::updateLicense(const String& sessionId, LicenseType, Ref<SharedBuffer>&& response, LicenseUpdateCallback&& callback)
480
void CDMInstanceSessionClearKey::updateLicense(const String& sessionId, LicenseType, Ref<FragmentedSharedBuffer>&& response, LicenseUpdateCallback&& callback)
479
{
481
{
480
#if LOG_DISABLED
482
#if LOG_DISABLED
481
    // We only use the sesion ID for debug logging. The verbose preprocessor checks are because
483
    // We only use the sesion ID for debug logging. The verbose preprocessor checks are because
Lines 566-572 void CDMInstanceSessionClearKey::removeSessionData(const String& sessionId, Lice a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp_sec12
566
    ASSERT(sessionId == m_sessionID);
568
    ASSERT(sessionId == m_sessionID);
567
569
568
    auto dispatchCallback =
570
    auto dispatchCallback =
569
        [weakThis = WeakPtr { *this }, &callback](KeyStatusVector&& keyStatusVector, std::optional<Ref<SharedBuffer>>&& message, SuccessValue success) {
571
        [weakThis = WeakPtr { *this }, &callback](KeyStatusVector&& keyStatusVector, std::optional<Ref<FragmentedSharedBuffer>>&& message, SuccessValue success) {
570
            callOnMainThread(
572
            callOnMainThread(
571
                [weakThis = WeakPtr { *weakThis }, callback = WTFMove(callback), keyStatusVector = WTFMove(keyStatusVector), message = WTFMove(message), success]() mutable {
573
                [weakThis = WeakPtr { *weakThis }, callback = WTFMove(callback), keyStatusVector = WTFMove(keyStatusVector), message = WTFMove(message), success]() mutable {
572
                    if (!weakThis)
574
                    if (!weakThis)
Lines 579-585 void CDMInstanceSessionClearKey::removeSessionData(const String& sessionId, Lice a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp_sec13
579
    // Construct the KeyStatusVector object, representing released keys, and the message in the
581
    // Construct the KeyStatusVector object, representing released keys, and the message in the
580
    // 'license release' format.
582
    // 'license release' format.
581
    KeyStatusVector keyStatusVector = m_keyStore.allKeysAs(CDMInstanceSession::KeyStatus::Released);
583
    KeyStatusVector keyStatusVector = m_keyStore.allKeysAs(CDMInstanceSession::KeyStatus::Released);
582
    RefPtr<SharedBuffer> message;
584
    RefPtr<FragmentedSharedBuffer> message;
583
    {
585
    {
584
        // Construct JSON that represents the 'license release' format, creating a 'kids' array
586
        // Construct JSON that represents the 'license release' format, creating a 'kids' array
585
        // of base64URL-encoded key IDs for all keys that were associated with this session.
587
        // of base64URL-encoded key IDs for all keys that were associated with this session.
Lines 593-606 void CDMInstanceSessionClearKey::removeSessionData(const String& sessionId, Lice a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.cpp_sec14
593
            rootObject->setArray("kids", WTFMove(array));
595
            rootObject->setArray("kids", WTFMove(array));
594
        }
596
        }
595
597
596
        // Copy the JSON data into a SharedBuffer object.
598
        // Copy the JSON data into a FragmentedSharedBuffer object.
597
        String messageString = rootObject->toJSONString();
599
        String messageString = rootObject->toJSONString();
598
        CString messageCString = messageString.utf8();
600
        CString messageCString = messageString.utf8();
599
        message = SharedBuffer::create(messageCString.data(), messageCString.length());
601
        message = SharedBuffer::create(messageCString.data(), messageCString.length());
600
    }
602
    }
601
603
602
    m_keyStore.unrefAllKeys();
604
    m_keyStore.unrefAllKeys();
603
    dispatchCallback(WTFMove(keyStatusVector), Ref<SharedBuffer>(*message), SuccessValue::Succeeded);
605
    dispatchCallback(WTFMove(keyStatusVector), Ref<FragmentedSharedBuffer>(*message), SuccessValue::Succeeded);
604
}
606
}
605
607
606
void CDMInstanceSessionClearKey::storeRecordOfKeyUsage(const String&)
608
void CDMInstanceSessionClearKey::storeRecordOfKeyUsage(const String&)
- a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.h -5 / +5 lines
Lines 86-93 public: a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.h_sec1
86
    void loadAndInitialize() final;
86
    void loadAndInitialize() final;
87
    bool supportsServerCertificates() const final;
87
    bool supportsServerCertificates() const final;
88
    bool supportsSessions() const final;
88
    bool supportsSessions() const final;
89
    bool supportsInitData(const AtomString&, const SharedBuffer&) const final;
89
    bool supportsInitData(const AtomString&, const FragmentedSharedBuffer&) const final;
90
    RefPtr<SharedBuffer> sanitizeResponse(const SharedBuffer&) const final;
90
    RefPtr<FragmentedSharedBuffer> sanitizeResponse(const FragmentedSharedBuffer&) const final;
91
    std::optional<String> sanitizeSessionId(const String&) const final;
91
    std::optional<String> sanitizeSessionId(const String&) const final;
92
};
92
};
93
93
Lines 99-105 public: a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.h_sec2
99
    // CDMInstance
99
    // CDMInstance
100
    ImplementationType implementationType() const final { return ImplementationType::ClearKey; }
100
    ImplementationType implementationType() const final { return ImplementationType::ClearKey; }
101
    void initializeWithConfiguration(const CDMKeySystemConfiguration&, AllowDistinctiveIdentifiers, AllowPersistentState, SuccessCallback&&) final;
101
    void initializeWithConfiguration(const CDMKeySystemConfiguration&, AllowDistinctiveIdentifiers, AllowPersistentState, SuccessCallback&&) final;
102
    void setServerCertificate(Ref<SharedBuffer>&&, SuccessCallback&&) final;
102
    void setServerCertificate(Ref<FragmentedSharedBuffer>&&, SuccessCallback&&) final;
103
    void setStorageDirectory(const String&) final;
103
    void setStorageDirectory(const String&) final;
104
    const String& keySystem() const final;
104
    const String& keySystem() const final;
105
    RefPtr<CDMInstanceSession> createSession() final;
105
    RefPtr<CDMInstanceSession> createSession() final;
Lines 109-116 class CDMInstanceSessionClearKey final : public CDMInstanceSessionProxy { a/Source/WebCore/platform/encryptedmedia/clearkey/CDMClearKey.h_sec3
109
public:
109
public:
110
    CDMInstanceSessionClearKey(CDMInstanceClearKey& parent)
110
    CDMInstanceSessionClearKey(CDMInstanceClearKey& parent)
111
        : CDMInstanceSessionProxy(parent) { }
111
        : CDMInstanceSessionProxy(parent) { }
112
    void requestLicense(LicenseType, const AtomString& initDataType, Ref<SharedBuffer>&& initData, LicenseCallback&&) final;
112
    void requestLicense(LicenseType, const AtomString& initDataType, Ref<FragmentedSharedBuffer>&& initData, LicenseCallback&&) final;
113
    void updateLicense(const String&, LicenseType, Ref<SharedBuffer>&&, LicenseUpdateCallback&&) final;
113
    void updateLicense(const String&, LicenseType, Ref<FragmentedSharedBuffer>&&, LicenseUpdateCallback&&) final;
114
    void loadSession(LicenseType, const String&, const String&, LoadSessionCallback&&) final;
114
    void loadSession(LicenseType, const String&, const String&, LoadSessionCallback&&) final;
115
    void closeSession(const String&, CloseSessionCallback&&) final;
115
    void closeSession(const String&, CloseSessionCallback&&) final;
116
    void removeSessionData(const String&, LicenseType, RemoveSessionDataCallback&&) final;
116
    void removeSessionData(const String&, LicenseType, RemoveSessionDataCallback&&) final;
- a/Source/WebCore/platform/generic/KeyedEncoderGeneric.h -1 / +1 lines
Lines 33-39 a/Source/WebCore/platform/generic/KeyedEncoderGeneric.h_sec1
33
33
34
namespace WebCore {
34
namespace WebCore {
35
35
36
class SharedBuffer;
36
class FragmentedSharedBuffer;
37
37
38
class KeyedEncoderGeneric final : public KeyedEncoder {
38
class KeyedEncoderGeneric final : public KeyedEncoder {
39
public:
39
public:
- a/Source/WebCore/platform/glib/SharedBufferGlib.cpp -3 / +3 lines
Lines 26-41 a/Source/WebCore/platform/glib/SharedBufferGlib.cpp_sec1
26
26
27
namespace WebCore {
27
namespace WebCore {
28
28
29
SharedBuffer::SharedBuffer(GBytes* bytes)
29
FragmentedSharedBuffer::FragmentedSharedBuffer(GBytes* bytes)
30
{
30
{
31
    ASSERT(bytes);
31
    ASSERT(bytes);
32
    m_size = g_bytes_get_size(bytes);
32
    m_size = g_bytes_get_size(bytes);
33
    m_segments.append({ 0, DataSegment::create(GRefPtr<GBytes>(bytes)) });
33
    m_segments.append({ 0, DataSegment::create(GRefPtr<GBytes>(bytes)) });
34
}
34
}
35
35
36
Ref<SharedBuffer> SharedBuffer::create(GBytes* bytes)
36
Ref<FragmentedSharedBuffer> FragmentedSharedBuffer::create(GBytes* bytes)
37
{
37
{
38
    return adoptRef(*new SharedBuffer(bytes));
38
    return adoptRef(*new FragmentedSharedBuffer(bytes));
39
}
39
}
40
40
41
GRefPtr<GBytes> SharedBuffer::createGBytes() const
41
GRefPtr<GBytes> SharedBuffer::createGBytes() const
- a/Source/WebCore/platform/graphics/Font.h -1 / +1 lines
Lines 59-65 namespace WebCore { a/Source/WebCore/platform/graphics/Font.h_sec1
59
class FontCache;
59
class FontCache;
60
class FontDescription;
60
class FontDescription;
61
class GlyphPage;
61
class GlyphPage;
62
class SharedBuffer;
62
class FragmentedSharedBuffer;
63
63
64
struct GlyphData;
64
struct GlyphData;
65
65
- a/Source/WebCore/platform/graphics/FontPlatformData.h -1 lines
Lines 74-80 interface IDWriteFontFace; a/Source/WebCore/platform/graphics/FontPlatformData.h_sec1
74
namespace WebCore {
74
namespace WebCore {
75
75
76
class FontDescription;
76
class FontDescription;
77
class SharedBuffer;
78
77
79
// This class is conceptually immutable. Once created, no instances should ever change (in an observable way).
78
// This class is conceptually immutable. Once created, no instances should ever change (in an observable way).
80
class FontPlatformData {
79
class FontPlatformData {
- a/Source/WebCore/platform/graphics/Image.cpp -1 / +1 lines
Lines 104-110 bool Image::isPostScriptResource(const String& mimeType, const URL& url) a/Source/WebCore/platform/graphics/Image.cpp_sec1
104
}
104
}
105
105
106
106
107
EncodedDataStatus Image::setData(RefPtr<SharedBuffer>&& data, bool allDataReceived)
107
EncodedDataStatus Image::setData(RefPtr<FragmentedSharedBuffer>&& data, bool allDataReceived)
108
{
108
{
109
    m_encodedImageData = WTFMove(data);
109
    m_encodedImageData = WTFMove(data);
110
110
- a/Source/WebCore/platform/graphics/Image.h -5 / +5 lines
Lines 70-76 class AffineTransform; a/Source/WebCore/platform/graphics/Image.h_sec1
70
class FloatPoint;
70
class FloatPoint;
71
class FloatSize;
71
class FloatSize;
72
class GraphicsContext;
72
class GraphicsContext;
73
class SharedBuffer;
73
class FragmentedSharedBuffer;
74
struct Length;
74
struct Length;
75
75
76
// This class gets notified when an image creates or destroys decoded frames and when it advances animation frames.
76
// This class gets notified when an image creates or destroys decoded frames and when it advances animation frames.
Lines 124-130 public: a/Source/WebCore/platform/graphics/Image.h_sec2
124
    virtual std::optional<IntPoint> hotSpot() const { return std::nullopt; }
124
    virtual std::optional<IntPoint> hotSpot() const { return std::nullopt; }
125
    virtual ImageOrientation orientation() const { return ImageOrientation::FromImage; }
125
    virtual ImageOrientation orientation() const { return ImageOrientation::FromImage; }
126
126
127
    WEBCORE_EXPORT EncodedDataStatus setData(RefPtr<SharedBuffer>&& data, bool allDataReceived);
127
    WEBCORE_EXPORT EncodedDataStatus setData(RefPtr<FragmentedSharedBuffer>&& data, bool allDataReceived);
128
    virtual EncodedDataStatus dataChanged(bool /*allDataReceived*/) { return EncodedDataStatus::Unknown; }
128
    virtual EncodedDataStatus dataChanged(bool /*allDataReceived*/) { return EncodedDataStatus::Unknown; }
129
129
130
    virtual String uti() const { return String(); } // null string if unknown
130
    virtual String uti() const { return String(); } // null string if unknown
Lines 133-140 public: a/Source/WebCore/platform/graphics/Image.h_sec3
133
133
134
    virtual void destroyDecodedData(bool destroyAll = true) = 0;
134
    virtual void destroyDecodedData(bool destroyAll = true) = 0;
135
135
136
    SharedBuffer* data() { return m_encodedImageData.get(); }
136
    FragmentedSharedBuffer* data() { return m_encodedImageData.get(); }
137
    const SharedBuffer* data() const { return m_encodedImageData.get(); }
137
    const FragmentedSharedBuffer* data() const { return m_encodedImageData.get(); }
138
138
139
    virtual DestinationColorSpace colorSpace();
139
    virtual DestinationColorSpace colorSpace();
140
140
Lines 209-215 protected: a/Source/WebCore/platform/graphics/Image.h_sec4
209
    virtual Color singlePixelSolidColor() const { return Color(); }
209
    virtual Color singlePixelSolidColor() const { return Color(); }
210
210
211
private:
211
private:
212
    RefPtr<SharedBuffer> m_encodedImageData;
212
    RefPtr<FragmentedSharedBuffer> m_encodedImageData;
213
    ImageObserver* m_imageObserver;
213
    ImageObserver* m_imageObserver;
214
    std::unique_ptr<Timer> m_animationStartTimer;
214
    std::unique_ptr<Timer> m_animationStartTimer;
215
};
215
};
- a/Source/WebCore/platform/graphics/ImageBackingStore.h -3 / +3 lines
Lines 66-72 public: a/Source/WebCore/platform/graphics/ImageBackingStore.h_sec1
66
            return false;
66
            return false;
67
67
68
        buffer.grow(bufferSize);
68
        buffer.grow(bufferSize);
69
        m_pixels = SharedBuffer::DataSegment::create(WTFMove(buffer));
69
        m_pixels = FragmentedSharedBuffer::DataSegment::create(WTFMove(buffer));
70
        m_pixelsPtr = reinterpret_cast<uint32_t*>(const_cast<uint8_t*>(m_pixels->data()));
70
        m_pixelsPtr = reinterpret_cast<uint32_t*>(const_cast<uint8_t*>(m_pixels->data()));
71
        m_size = size;
71
        m_size = size;
72
        m_frameRect = IntRect(IntPoint(), m_size);
72
        m_frameRect = IntRect(IntPoint(), m_size);
Lines 206-212 private: a/Source/WebCore/platform/graphics/ImageBackingStore.h_sec2
206
    {
206
    {
207
        ASSERT(!m_size.isEmpty() && !isOverSize(m_size));
207
        ASSERT(!m_size.isEmpty() && !isOverSize(m_size));
208
        Vector<uint8_t> buffer { other.m_pixels->data(), other.m_pixels->size() };
208
        Vector<uint8_t> buffer { other.m_pixels->data(), other.m_pixels->size() };
209
        m_pixels = SharedBuffer::DataSegment::create(WTFMove(buffer));
209
        m_pixels = FragmentedSharedBuffer::DataSegment::create(WTFMove(buffer));
210
        m_pixelsPtr = reinterpret_cast<uint32_t*>(const_cast<uint8_t*>(m_pixels->data()));
210
        m_pixelsPtr = reinterpret_cast<uint32_t*>(const_cast<uint8_t*>(m_pixels->data()));
211
    }
211
    }
212
212
Lines 233-239 private: a/Source/WebCore/platform/graphics/ImageBackingStore.h_sec3
233
        return PackedColor::ARGB { result }.value;
233
        return PackedColor::ARGB { result }.value;
234
    }
234
    }
235
235
236
    RefPtr<SharedBuffer::DataSegment> m_pixels;
236
    RefPtr<FragmentedSharedBuffer::DataSegment> m_pixels;
237
    uint32_t* m_pixelsPtr { nullptr };
237
    uint32_t* m_pixelsPtr { nullptr };
238
    IntSize m_size;
238
    IntSize m_size;
239
    IntRect m_frameRect; // This will always just be the entire buffer except for GIF and PNG frames
239
    IntRect m_frameRect; // This will always just be the entire buffer except for GIF and PNG frames
- a/Source/WebCore/platform/graphics/ImageDecoder.cpp -1 / +1 lines
Lines 82-88 void ImageDecoder::clearFactories() a/Source/WebCore/platform/graphics/ImageDecoder.cpp_sec1
82
}
82
}
83
#endif
83
#endif
84
84
85
RefPtr<ImageDecoder> ImageDecoder::create(SharedBuffer& data, const String& mimeType, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
85
RefPtr<ImageDecoder> ImageDecoder::create(FragmentedSharedBuffer& data, const String& mimeType, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
86
{
86
{
87
    UNUSED_PARAM(mimeType);
87
    UNUSED_PARAM(mimeType);
88
88
- a/Source/WebCore/platform/graphics/ImageDecoder.h -4 / +4 lines
Lines 37-48 a/Source/WebCore/platform/graphics/ImageDecoder.h_sec1
37
37
38
namespace WebCore {
38
namespace WebCore {
39
39
40
class SharedBuffer;
40
class FragmentedSharedBuffer;
41
41
42
class ImageDecoder : public ThreadSafeRefCounted<ImageDecoder> {
42
class ImageDecoder : public ThreadSafeRefCounted<ImageDecoder> {
43
    WTF_MAKE_FAST_ALLOCATED;
43
    WTF_MAKE_FAST_ALLOCATED;
44
public:
44
public:
45
    static RefPtr<ImageDecoder> create(SharedBuffer&, const String& mimeType, AlphaOption, GammaAndColorProfileOption);
45
    static RefPtr<ImageDecoder> create(FragmentedSharedBuffer&, const String& mimeType, AlphaOption, GammaAndColorProfileOption);
46
    virtual ~ImageDecoder() = default;
46
    virtual ~ImageDecoder() = default;
47
47
48
    enum class MediaType {
48
    enum class MediaType {
Lines 91-97 public: a/Source/WebCore/platform/graphics/ImageDecoder.h_sec2
91
#if ENABLE(GPU_PROCESS)
91
#if ENABLE(GPU_PROCESS)
92
    using SupportsMediaTypeFunc = Function<bool(MediaType)>;
92
    using SupportsMediaTypeFunc = Function<bool(MediaType)>;
93
    using CanDecodeTypeFunc = Function<bool(const String&)>;
93
    using CanDecodeTypeFunc = Function<bool(const String&)>;
94
    using CreateImageDecoderFunc = Function<RefPtr<ImageDecoder>(SharedBuffer&, const String&, AlphaOption, GammaAndColorProfileOption)>;
94
    using CreateImageDecoderFunc = Function<RefPtr<ImageDecoder>(FragmentedSharedBuffer&, const String&, AlphaOption, GammaAndColorProfileOption)>;
95
95
96
    struct ImageDecoderFactory {
96
    struct ImageDecoderFactory {
97
        SupportsMediaTypeFunc supportsMediaType;
97
        SupportsMediaTypeFunc supportsMediaType;
Lines 129-135 public: a/Source/WebCore/platform/graphics/ImageDecoder.h_sec3
129
    virtual PlatformImagePtr createFrameImageAtIndex(size_t, SubsamplingLevel = SubsamplingLevel::Default, const DecodingOptions& = DecodingOptions(DecodingMode::Synchronous)) = 0;
129
    virtual PlatformImagePtr createFrameImageAtIndex(size_t, SubsamplingLevel = SubsamplingLevel::Default, const DecodingOptions& = DecodingOptions(DecodingMode::Synchronous)) = 0;
130
130
131
    virtual void setExpectedContentSize(long long) { }
131
    virtual void setExpectedContentSize(long long) { }
132
    virtual void setData(SharedBuffer&, bool allDataReceived) = 0;
132
    virtual void setData(FragmentedSharedBuffer&, bool allDataReceived) = 0;
133
    virtual bool isAllDataReceived() const = 0;
133
    virtual bool isAllDataReceived() const = 0;
134
    virtual void clearFrameBufferCache(size_t) = 0;
134
    virtual void clearFrameBufferCache(size_t) = 0;
135
135
- a/Source/WebCore/platform/graphics/ImageSource.cpp -4 / +4 lines
Lines 72-78 ImageSource::~ImageSource() a/Source/WebCore/platform/graphics/ImageSource.cpp_sec1
72
    ASSERT(&m_runLoop == &RunLoop::current());
72
    ASSERT(&m_runLoop == &RunLoop::current());
73
}
73
}
74
74
75
bool ImageSource::ensureDecoderAvailable(SharedBuffer* data)
75
bool ImageSource::ensureDecoderAvailable(FragmentedSharedBuffer* data)
76
{
76
{
77
    if (!data || isDecoderAvailable())
77
    if (!data || isDecoderAvailable())
78
        return true;
78
        return true;
Lines 96-102 bool ImageSource::ensureDecoderAvailable(SharedBuffer* data) a/Source/WebCore/platform/graphics/ImageSource.cpp_sec2
96
    return true;
96
    return true;
97
}
97
}
98
98
99
void ImageSource::setData(SharedBuffer* data, bool allDataReceived)
99
void ImageSource::setData(FragmentedSharedBuffer* data, bool allDataReceived)
100
{
100
{
101
    if (!data || !ensureDecoderAvailable(data))
101
    if (!data || !ensureDecoderAvailable(data))
102
        return;
102
        return;
Lines 104-116 void ImageSource::setData(SharedBuffer* data, bool allDataReceived) a/Source/WebCore/platform/graphics/ImageSource.cpp_sec3
104
    m_decoder->setData(*data, allDataReceived);
104
    m_decoder->setData(*data, allDataReceived);
105
}
105
}
106
106
107
void ImageSource::resetData(SharedBuffer* data)
107
void ImageSource::resetData(FragmentedSharedBuffer* data)
108
{
108
{
109
    m_decoder = nullptr;
109
    m_decoder = nullptr;
110
    setData(data, isAllDataReceived());
110
    setData(data, isAllDataReceived());
111
}
111
}
112
112
113
EncodedDataStatus ImageSource::dataChanged(SharedBuffer* data, bool allDataReceived)
113
EncodedDataStatus ImageSource::dataChanged(FragmentedSharedBuffer* data, bool allDataReceived)
114
{
114
{
115
    setData(data, allDataReceived);
115
    setData(data, allDataReceived);
116
    clearMetadata();
116
    clearMetadata();
- a/Source/WebCore/platform/graphics/ImageSource.h -5 / +5 lines
Lines 39-45 namespace WebCore { a/Source/WebCore/platform/graphics/ImageSource.h_sec1
39
class BitmapImage;
39
class BitmapImage;
40
class GraphicsContext;
40
class GraphicsContext;
41
class ImageDecoder;
41
class ImageDecoder;
42
class SharedBuffer;
42
class FragmentedSharedBuffer;
43
43
44
class ImageSource : public ThreadSafeRefCounted<ImageSource>, public CanMakeWeakPtr<ImageSource> {
44
class ImageSource : public ThreadSafeRefCounted<ImageSource>, public CanMakeWeakPtr<ImageSource> {
45
    friend class BitmapImage;
45
    friend class BitmapImage;
Lines 56-64 public: a/Source/WebCore/platform/graphics/ImageSource.h_sec2
56
        return adoptRef(*new ImageSource(WTFMove(nativeImage)));
56
        return adoptRef(*new ImageSource(WTFMove(nativeImage)));
57
    }
57
    }
58
58
59
    void setData(SharedBuffer* data, bool allDataReceived);
59
    void setData(FragmentedSharedBuffer* data, bool allDataReceived);
60
    void resetData(SharedBuffer* data);
60
    void resetData(FragmentedSharedBuffer* data);
61
    EncodedDataStatus dataChanged(SharedBuffer* data, bool allDataReceived);
61
    EncodedDataStatus dataChanged(FragmentedSharedBuffer* data, bool allDataReceived);
62
    bool isAllDataReceived();
62
    bool isAllDataReceived();
63
63
64
    unsigned decodedSize() const { return m_decodedSize; }
64
    unsigned decodedSize() const { return m_decodedSize; }
Lines 154-160 private: a/Source/WebCore/platform/graphics/ImageSource.h_sec3
154
    template<typename T>
154
    template<typename T>
155
    T firstFrameMetadataCacheIfNeeded(T& cachedValue, MetadataType, T (ImageFrame::*functor)() const, ImageFrame::Caching, const std::optional<SubsamplingLevel>& = { });
155
    T firstFrameMetadataCacheIfNeeded(T& cachedValue, MetadataType, T (ImageFrame::*functor)() const, ImageFrame::Caching, const std::optional<SubsamplingLevel>& = { });
156
156
157
    bool ensureDecoderAvailable(SharedBuffer* data);
157
    bool ensureDecoderAvailable(FragmentedSharedBuffer* data);
158
    bool isDecoderAvailable() const { return m_decoder; }
158
    bool isDecoderAvailable() const { return m_decoder; }
159
    void destroyDecodedData(size_t frameCount, size_t excludeFrame);
159
    void destroyDecodedData(size_t frameCount, size_t excludeFrame);
160
    void decodedSizeChanged(long long decodedSize);
160
    void decodedSizeChanged(long long decodedSize);
- a/Source/WebCore/platform/graphics/Model.cpp -2 / +2 lines
Lines 30-41 a/Source/WebCore/platform/graphics/Model.cpp_sec1
30
30
31
namespace WebCore {
31
namespace WebCore {
32
32
33
Ref<Model> Model::create(Ref<SharedBuffer> data, String mimeType, URL url)
33
Ref<Model> Model::create(Ref<SharedBuffer>&& data, String mimeType, URL url)
34
{
34
{
35
    return adoptRef(*new Model(WTFMove(data), WTFMove(mimeType), WTFMove(url)));
35
    return adoptRef(*new Model(WTFMove(data), WTFMove(mimeType), WTFMove(url)));
36
}
36
}
37
37
38
Model::Model(Ref<SharedBuffer> data, String mimeType, URL url)
38
Model::Model(Ref<SharedBuffer>&& data, String mimeType, URL url)
39
    : m_data(WTFMove(data))
39
    : m_data(WTFMove(data))
40
    , m_mimeType(WTFMove(mimeType))
40
    , m_mimeType(WTFMove(mimeType))
41
    , m_url(WTFMove(url))
41
    , m_url(WTFMove(url))
- a/Source/WebCore/platform/graphics/Model.h -3 / +3 lines
Lines 38-44 namespace WebCore { a/Source/WebCore/platform/graphics/Model.h_sec1
38
38
39
class Model final : public RefCounted<Model> {
39
class Model final : public RefCounted<Model> {
40
public:
40
public:
41
    WEBCORE_EXPORT static Ref<Model> create(Ref<SharedBuffer>, String, URL);
41
    WEBCORE_EXPORT static Ref<Model> create(Ref<SharedBuffer>&&, String, URL);
42
    WEBCORE_EXPORT ~Model();
42
    WEBCORE_EXPORT ~Model();
43
43
44
    Ref<SharedBuffer> data() const { return m_data; }
44
    Ref<SharedBuffer> data() const { return m_data; }
Lines 49-55 public: a/Source/WebCore/platform/graphics/Model.h_sec2
49
    template<class Decoder> static RefPtr<Model> decode(Decoder&);
49
    template<class Decoder> static RefPtr<Model> decode(Decoder&);
50
50
51
private:
51
private:
52
    explicit Model(Ref<SharedBuffer>, String, URL);
52
    explicit Model(Ref<SharedBuffer>&&, String, URL);
53
53
54
    Ref<SharedBuffer> m_data;
54
    Ref<SharedBuffer> m_data;
55
    String m_mimeType;
55
    String m_mimeType;
Lines 60-66 template<class Encoder> a/Source/WebCore/platform/graphics/Model.h_sec3
60
void Model::encode(Encoder& encoder) const
60
void Model::encode(Encoder& encoder) const
61
{
61
{
62
    encoder << static_cast<size_t>(m_data->size());
62
    encoder << static_cast<size_t>(m_data->size());
63
    encoder.encodeFixedLengthData(m_data->data(), m_data->size(), 1);
63
    encoder.encodeFixedLengthData(m_data->makeContiguous()->data(), m_data->size(), 1);
64
    encoder << m_mimeType;
64
    encoder << m_mimeType;
65
    encoder << m_url;
65
    encoder << m_url;
66
}
66
}
- a/Source/WebCore/platform/graphics/PlatformMediaResourceLoader.h -2 / +2 lines
Lines 51-58 public: a/Source/WebCore/platform/graphics/PlatformMediaResourceLoader.h_sec1
51
    virtual void redirectReceived(PlatformMediaResource&, ResourceRequest&& request, const ResourceResponse&, CompletionHandler<void(ResourceRequest&&)>&& completionHandler) { completionHandler(WTFMove(request)); }
51
    virtual void redirectReceived(PlatformMediaResource&, ResourceRequest&& request, const ResourceResponse&, CompletionHandler<void(ResourceRequest&&)>&& completionHandler) { completionHandler(WTFMove(request)); }
52
    virtual bool shouldCacheResponse(PlatformMediaResource&, const ResourceResponse&) { return true; }
52
    virtual bool shouldCacheResponse(PlatformMediaResource&, const ResourceResponse&) { return true; }
53
    virtual void dataSent(PlatformMediaResource&, unsigned long long, unsigned long long) { }
53
    virtual void dataSent(PlatformMediaResource&, unsigned long long, unsigned long long) { }
54
    virtual void dataReceived(PlatformMediaResource&, Ref<SharedBuffer>&&) { RELEASE_ASSERT_NOT_REACHED(); }
54
    virtual void dataReceived(PlatformMediaResource&, Ref<FragmentedSharedBuffer>&&) { RELEASE_ASSERT_NOT_REACHED(); }
55
    // This method should be removed once CachedRawResourceClient uses SharedBuffer.
55
    // This method should be removed once CachedRawResourceClient uses FragmentedSharedBuffer.
56
    virtual void dataReceived(PlatformMediaResource& platform, const uint8_t* data, int length) { dataReceived(platform, SharedBuffer::create(data, length)); }
56
    virtual void dataReceived(PlatformMediaResource& platform, const uint8_t* data, int length) { dataReceived(platform, SharedBuffer::create(data, length)); }
57
    virtual void accessControlCheckFailed(PlatformMediaResource&, const ResourceError&) { }
57
    virtual void accessControlCheckFailed(PlatformMediaResource&, const ResourceError&) { }
58
    virtual void loadFailed(PlatformMediaResource&, const ResourceError&) { }
58
    virtual void loadFailed(PlatformMediaResource&, const ResourceError&) { }
- a/Source/WebCore/platform/graphics/avfoundation/CDMFairPlayStreaming.cpp -12 / +12 lines
Lines 86-97 const AtomString& CDMPrivateFairPlayStreaming::skdName() a/Source/WebCore/platform/graphics/avfoundation/CDMFairPlayStreaming.cpp_sec1
86
    return skd;
86
    return skd;
87
}
87
}
88
88
89
static Vector<Ref<SharedBuffer>> extractSinfData(const SharedBuffer& buffer)
89
static Vector<Ref<FragmentedSharedBuffer>> extractSinfData(const FragmentedSharedBuffer& buffer)
90
{
90
{
91
    // JSON of the format: "{ sinf: [ <base64-encoded-string> ] }"
91
    // JSON of the format: "{ sinf: [ <base64-encoded-string> ] }"
92
    if (buffer.size() > std::numeric_limits<unsigned>::max())
92
    if (buffer.size() > std::numeric_limits<unsigned>::max())
93
        return { };
93
        return { };
94
    String json { buffer.data(), static_cast<unsigned>(buffer.size()) };
94
    String json { buffer.makeContiguous()->data(), static_cast<unsigned>(buffer.size()) };
95
95
96
    auto value = JSON::Value::parseJSON(json);
96
    auto value = JSON::Value::parseJSON(json);
97
    if (!value)
97
    if (!value)
Lines 105-111 static Vector<Ref<SharedBuffer>> extractSinfData(const SharedBuffer& buffer) a/Source/WebCore/platform/graphics/avfoundation/CDMFairPlayStreaming.cpp_sec2
105
    if (!sinfArray)
105
    if (!sinfArray)
106
        return { };
106
        return { };
107
107
108
    Vector<Ref<SharedBuffer>> sinfs;
108
    Vector<Ref<FragmentedSharedBuffer>> sinfs;
109
    sinfs.reserveInitialCapacity(sinfArray->length());
109
    sinfs.reserveInitialCapacity(sinfArray->length());
110
110
111
    for (auto& value : *sinfArray) {
111
    for (auto& value : *sinfArray) {
Lines 124-130 static Vector<Ref<SharedBuffer>> extractSinfData(const SharedBuffer& buffer) a/Source/WebCore/platform/graphics/avfoundation/CDMFairPlayStreaming.cpp_sec3
124
}
124
}
125
125
126
using SchemeAndKeyResult = Vector<std::pair<FourCC, Vector<uint8_t>>>;
126
using SchemeAndKeyResult = Vector<std::pair<FourCC, Vector<uint8_t>>>;
127
static SchemeAndKeyResult extractSchemeAndKeyIdFromSinf(const SharedBuffer& buffer)
127
static SchemeAndKeyResult extractSchemeAndKeyIdFromSinf(const FragmentedSharedBuffer& buffer)
128
{
128
{
129
    auto buffers = extractSinfData(buffer);
129
    auto buffers = extractSinfData(buffer);
130
    if (!buffers.size())
130
    if (!buffers.size())
Lines 170-178 static SchemeAndKeyResult extractSchemeAndKeyIdFromSinf(const SharedBuffer& buff a/Source/WebCore/platform/graphics/avfoundation/CDMFairPlayStreaming.cpp_sec4
170
    return result;
170
    return result;
171
}
171
}
172
172
173
std::optional<Vector<Ref<SharedBuffer>>> CDMPrivateFairPlayStreaming::extractKeyIDsSinf(const SharedBuffer& buffer)
173
std::optional<Vector<Ref<FragmentedSharedBuffer>>> CDMPrivateFairPlayStreaming::extractKeyIDsSinf(const FragmentedSharedBuffer& buffer)
174
{
174
{
175
    Vector<Ref<SharedBuffer>> keyIDs;
175
    Vector<Ref<FragmentedSharedBuffer>> keyIDs;
176
    auto results = extractSchemeAndKeyIdFromSinf(buffer);
176
    auto results = extractSchemeAndKeyIdFromSinf(buffer);
177
177
178
    for (auto& result : results) {
178
    for (auto& result : results) {
Lines 183-189 std::optional<Vector<Ref<SharedBuffer>>> CDMPrivateFairPlayStreaming::extractKey a/Source/WebCore/platform/graphics/avfoundation/CDMFairPlayStreaming.cpp_sec5
183
    return keyIDs;
183
    return keyIDs;
184
}
184
}
185
185
186
RefPtr<SharedBuffer> CDMPrivateFairPlayStreaming::sanitizeSinf(const SharedBuffer& buffer)
186
RefPtr<FragmentedSharedBuffer> CDMPrivateFairPlayStreaming::sanitizeSinf(const FragmentedSharedBuffer& buffer)
187
{
187
{
188
    // Common SINF Box Format
188
    // Common SINF Box Format
189
    UNUSED_PARAM(buffer);
189
    UNUSED_PARAM(buffer);
Lines 191-207 RefPtr<SharedBuffer> CDMPrivateFairPlayStreaming::sanitizeSinf(const SharedBuffe a/Source/WebCore/platform/graphics/avfoundation/CDMFairPlayStreaming.cpp_sec6
191
    return buffer.copy();
191
    return buffer.copy();
192
}
192
}
193
193
194
RefPtr<SharedBuffer> CDMPrivateFairPlayStreaming::sanitizeSkd(const SharedBuffer& buffer)
194
RefPtr<FragmentedSharedBuffer> CDMPrivateFairPlayStreaming::sanitizeSkd(const FragmentedSharedBuffer& buffer)
195
{
195
{
196
    UNUSED_PARAM(buffer);
196
    UNUSED_PARAM(buffer);
197
    notImplemented();
197
    notImplemented();
198
    return buffer.copy();
198
    return buffer.copy();
199
}
199
}
200
200
201
std::optional<Vector<Ref<SharedBuffer>>> CDMPrivateFairPlayStreaming::extractKeyIDsSkd(const SharedBuffer& buffer)
201
std::optional<Vector<Ref<FragmentedSharedBuffer>>> CDMPrivateFairPlayStreaming::extractKeyIDsSkd(const FragmentedSharedBuffer& buffer)
202
{
202
{
203
    // In the 'skd' scheme, the init data is the key ID.
203
    // In the 'skd' scheme, the init data is the key ID.
204
    Vector<Ref<SharedBuffer>> keyIDs;
204
    Vector<Ref<FragmentedSharedBuffer>> keyIDs;
205
    keyIDs.append(buffer.copy());
205
    keyIDs.append(buffer.copy());
206
    return keyIDs;
206
    return keyIDs;
207
}
207
}
Lines 393-399 bool CDMPrivateFairPlayStreaming::supportsSessions() const a/Source/WebCore/platform/graphics/avfoundation/CDMFairPlayStreaming.cpp_sec7
393
    return true;
393
    return true;
394
}
394
}
395
395
396
bool CDMPrivateFairPlayStreaming::supportsInitData(const AtomString& initDataType, const SharedBuffer& initData) const
396
bool CDMPrivateFairPlayStreaming::supportsInitData(const AtomString& initDataType, const FragmentedSharedBuffer& initData) const
397
{
397
{
398
    if (!validInitDataTypes().contains(initDataType))
398
    if (!validInitDataTypes().contains(initDataType))
399
        return false;
399
        return false;
Lines 423-429 bool CDMPrivateFairPlayStreaming::supportsInitData(const AtomString& initDataTyp a/Source/WebCore/platform/graphics/avfoundation/CDMFairPlayStreaming.cpp_sec8
423
    return false;
423
    return false;
424
}
424
}
425
425
426
RefPtr<SharedBuffer> CDMPrivateFairPlayStreaming::sanitizeResponse(const SharedBuffer& response) const
426
RefPtr<FragmentedSharedBuffer> CDMPrivateFairPlayStreaming::sanitizeResponse(const FragmentedSharedBuffer& response) const
427
{
427
{
428
    return response.copy();
428
    return response.copy();
429
}
429
}
- a/Source/WebCore/platform/graphics/avfoundation/CDMFairPlayStreaming.h -6 / +6 lines
Lines 71-87 public: a/Source/WebCore/platform/graphics/avfoundation/CDMFairPlayStreaming.h_sec1
71
    void loadAndInitialize() override;
71
    void loadAndInitialize() override;
72
    bool supportsServerCertificates() const override;
72
    bool supportsServerCertificates() const override;
73
    bool supportsSessions() const override;
73
    bool supportsSessions() const override;
74
    bool supportsInitData(const AtomString&, const SharedBuffer&) const override;
74
    bool supportsInitData(const AtomString&, const FragmentedSharedBuffer&) const override;
75
    RefPtr<SharedBuffer> sanitizeResponse(const SharedBuffer&) const override;
75
    RefPtr<FragmentedSharedBuffer> sanitizeResponse(const FragmentedSharedBuffer&) const override;
76
    std::optional<String> sanitizeSessionId(const String&) const override;
76
    std::optional<String> sanitizeSessionId(const String&) const override;
77
77
78
    static const AtomString& sinfName();
78
    static const AtomString& sinfName();
79
    static std::optional<Vector<Ref<SharedBuffer>>> extractKeyIDsSinf(const SharedBuffer&);
79
    static std::optional<Vector<Ref<FragmentedSharedBuffer>>> extractKeyIDsSinf(const FragmentedSharedBuffer&);
80
    static RefPtr<SharedBuffer> sanitizeSinf(const SharedBuffer&);
80
    static RefPtr<FragmentedSharedBuffer> sanitizeSinf(const FragmentedSharedBuffer&);
81
81
82
    static const AtomString& skdName();
82
    static const AtomString& skdName();
83
    static std::optional<Vector<Ref<SharedBuffer>>> extractKeyIDsSkd(const SharedBuffer&);
83
    static std::optional<Vector<Ref<FragmentedSharedBuffer>>> extractKeyIDsSkd(const FragmentedSharedBuffer&);
84
    static RefPtr<SharedBuffer> sanitizeSkd(const SharedBuffer&);
84
    static RefPtr<FragmentedSharedBuffer> sanitizeSkd(const FragmentedSharedBuffer&);
85
85
86
    static const Vector<FourCC>& validFairPlayStreamingSchemes();
86
    static const Vector<FourCC>& validFairPlayStreamingSchemes();
87
87
- a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.h -7 / +7 lines
Lines 84-90 public: a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.h_sec1
84
    ImplementationType implementationType() const final { return ImplementationType::FairPlayStreaming; }
84
    ImplementationType implementationType() const final { return ImplementationType::FairPlayStreaming; }
85
85
86
    void initializeWithConfiguration(const CDMKeySystemConfiguration&, AllowDistinctiveIdentifiers, AllowPersistentState, SuccessCallback&&) final;
86
    void initializeWithConfiguration(const CDMKeySystemConfiguration&, AllowDistinctiveIdentifiers, AllowPersistentState, SuccessCallback&&) final;
87
    void setServerCertificate(Ref<SharedBuffer>&&, SuccessCallback&&) final;
87
    void setServerCertificate(Ref<FragmentedSharedBuffer>&&, SuccessCallback&&) final;
88
    void setStorageDirectory(const String&) final;
88
    void setStorageDirectory(const String&) final;
89
    RefPtr<CDMInstanceSession> createSession() final;
89
    RefPtr<CDMInstanceSession> createSession() final;
90
    void setClient(WeakPtr<CDMInstanceClient>&&) final;
90
    void setClient(WeakPtr<CDMInstanceClient>&&) final;
Lines 94-103 public: a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.h_sec2
94
94
95
    NSURL *storageURL() const { return m_storageURL.get(); }
95
    NSURL *storageURL() const { return m_storageURL.get(); }
96
    bool persistentStateAllowed() const { return m_persistentStateAllowed; }
96
    bool persistentStateAllowed() const { return m_persistentStateAllowed; }
97
    SharedBuffer* serverCertificate() const { return m_serverCertificate.get(); }
97
    FragmentedSharedBuffer* serverCertificate() const { return m_serverCertificate.get(); }
98
    AVContentKeySession* contentKeySession();
98
    AVContentKeySession* contentKeySession();
99
99
100
    RetainPtr<AVContentKeyRequest> takeUnexpectedKeyRequestForInitializationData(const AtomString& initDataType, SharedBuffer& initData);
100
    RetainPtr<AVContentKeyRequest> takeUnexpectedKeyRequestForInitializationData(const AtomString& initDataType, FragmentedSharedBuffer& initData);
101
101
102
    // AVContentKeySessionDelegateClient
102
    // AVContentKeySessionDelegateClient
103
    void didProvideRequest(AVContentKeyRequest*) final;
103
    void didProvideRequest(AVContentKeyRequest*) final;
Lines 112-118 public: a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.h_sec3
112
    void outputObscuredDueToInsufficientExternalProtectionChanged(bool) final;
112
    void outputObscuredDueToInsufficientExternalProtectionChanged(bool) final;
113
    void externalProtectionStatusDidChangeForContentKeyRequest(AVContentKeyRequest*) final;
113
    void externalProtectionStatusDidChangeForContentKeyRequest(AVContentKeyRequest*) final;
114
114
115
    using Keys = Vector<Ref<SharedBuffer>>;
115
    using Keys = Vector<Ref<FragmentedSharedBuffer>>;
116
    CDMInstanceSessionFairPlayStreamingAVFObjC* sessionForKeyIDs(const Keys&) const;
116
    CDMInstanceSessionFairPlayStreamingAVFObjC* sessionForKeyIDs(const Keys&) const;
117
    CDMInstanceSessionFairPlayStreamingAVFObjC* sessionForGroup(AVContentKeyReportGroup*) const;
117
    CDMInstanceSessionFairPlayStreamingAVFObjC* sessionForGroup(AVContentKeyReportGroup*) const;
118
    CDMInstanceSessionFairPlayStreamingAVFObjC* sessionForRequest(AVContentKeyRequest*) const;
118
    CDMInstanceSessionFairPlayStreamingAVFObjC* sessionForRequest(AVContentKeyRequest*) const;
Lines 129-135 private: a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.h_sec4
129
    WeakPtr<CDMInstanceClient> m_client;
129
    WeakPtr<CDMInstanceClient> m_client;
130
    RetainPtr<AVContentKeySession> m_session;
130
    RetainPtr<AVContentKeySession> m_session;
131
    RetainPtr<WebCoreFPSContentKeySessionDelegate> m_delegate;
131
    RetainPtr<WebCoreFPSContentKeySessionDelegate> m_delegate;
132
    RefPtr<SharedBuffer> m_serverCertificate;
132
    RefPtr<FragmentedSharedBuffer> m_serverCertificate;
133
    bool m_persistentStateAllowed { true };
133
    bool m_persistentStateAllowed { true };
134
    RetainPtr<NSURL> m_storageURL;
134
    RetainPtr<NSURL> m_storageURL;
135
    Vector<WeakPtr<CDMInstanceSessionFairPlayStreamingAVFObjC>> m_sessions;
135
    Vector<WeakPtr<CDMInstanceSessionFairPlayStreamingAVFObjC>> m_sessions;
Lines 150-157 public: a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.h_sec5
150
#endif
150
#endif
151
151
152
    // CDMInstanceSession
152
    // CDMInstanceSession
153
    void requestLicense(LicenseType, const AtomString& initDataType, Ref<SharedBuffer>&& initData, LicenseCallback&&) final;
153
    void requestLicense(LicenseType, const AtomString& initDataType, Ref<FragmentedSharedBuffer>&& initData, LicenseCallback&&) final;
154
    void updateLicense(const String&, LicenseType, Ref<SharedBuffer>&&, LicenseUpdateCallback&&) final;
154
    void updateLicense(const String&, LicenseType, Ref<FragmentedSharedBuffer>&&, LicenseUpdateCallback&&) final;
155
    void loadSession(LicenseType, const String&, const String&, LoadSessionCallback&&) final;
155
    void loadSession(LicenseType, const String&, const String&, LoadSessionCallback&&) final;
156
    void closeSession(const String&, CloseSessionCallback&&) final;
156
    void closeSession(const String&, CloseSessionCallback&&) final;
157
    void removeSessionData(const String&, LicenseType, RemoveSessionDataCallback&&) final;
157
    void removeSessionData(const String&, LicenseType, RemoveSessionDataCallback&&) final;
- a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm -28 / +28 lines
Lines 217-223 ALLOW_NEW_API_WITHOUT_GUARDS_END a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec1
217
    return AtomString(nsInitType);
217
    return AtomString(nsInitType);
218
}
218
}
219
219
220
static Ref<SharedBuffer> initializationDataForRequest(AVContentKeyRequest* request)
220
static Ref<FragmentedSharedBuffer> initializationDataForRequest(AVContentKeyRequest* request)
221
{
221
{
222
    if (!request)
222
    if (!request)
223
        return SharedBuffer::create();
223
        return SharedBuffer::create();
Lines 265-271 AVContentKeySession* CDMInstanceFairPlayStreamingAVFObjC::contentKeySession() a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec2
265
    return m_session.get();
265
    return m_session.get();
266
}
266
}
267
267
268
RetainPtr<AVContentKeyRequest> CDMInstanceFairPlayStreamingAVFObjC::takeUnexpectedKeyRequestForInitializationData(const AtomString& initDataType, SharedBuffer& initData)
268
RetainPtr<AVContentKeyRequest> CDMInstanceFairPlayStreamingAVFObjC::takeUnexpectedKeyRequestForInitializationData(const AtomString& initDataType, FragmentedSharedBuffer& initData)
269
{
269
{
270
    for (auto requestIter = m_unexpectedKeyRequests.begin(); requestIter != m_unexpectedKeyRequests.end(); ++requestIter) {
270
    for (auto requestIter = m_unexpectedKeyRequests.begin(); requestIter != m_unexpectedKeyRequests.end(); ++requestIter) {
271
        auto& request = *requestIter;
271
        auto& request = *requestIter;
Lines 316-322 private: a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec3
316
    ResponseMap m_responses;
316
    ResponseMap m_responses;
317
};
317
};
318
318
319
static RefPtr<JSON::Value> parseJSONValue(const SharedBuffer& buffer)
319
static RefPtr<JSON::Value> parseJSONValue(const FragmentedSharedBuffer& buffer)
320
{
320
{
321
    // Fail on large buffers whose size doesn't fit into a 32-bit unsigned integer.
321
    // Fail on large buffers whose size doesn't fit into a 32-bit unsigned integer.
322
    size_t size = buffer.size();
322
    size_t size = buffer.size();
Lines 324-330 static RefPtr<JSON::Value> parseJSONValue(const SharedBuffer& buffer) a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec4
324
        return nullptr;
324
        return nullptr;
325
325
326
    // Parse the buffer contents as JSON, returning the root object (if any).
326
    // Parse the buffer contents as JSON, returning the root object (if any).
327
    String json { buffer.data(), static_cast<unsigned>(size) };
327
    String json { buffer.makeContiguous()->data(), static_cast<unsigned>(size) };
328
328
329
    return JSON::Value::parseJSON(json);
329
    return JSON::Value::parseJSON(json);
330
}
330
}
Lines 380-386 void CDMInstanceFairPlayStreamingAVFObjC::initializeWithConfiguration(const CDMK a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec5
380
    callback(initialize());
380
    callback(initialize());
381
}
381
}
382
382
383
void CDMInstanceFairPlayStreamingAVFObjC::setServerCertificate(Ref<SharedBuffer>&& serverCertificate, SuccessCallback&& callback)
383
void CDMInstanceFairPlayStreamingAVFObjC::setServerCertificate(Ref<FragmentedSharedBuffer>&& serverCertificate, SuccessCallback&& callback)
384
{
384
{
385
    DEBUG_LOG_IF_POSSIBLE(LOGIDENTIFIER);
385
    DEBUG_LOG_IF_POSSIBLE(LOGIDENTIFIER);
386
    m_serverCertificate = WTFMove(serverCertificate);
386
    m_serverCertificate = WTFMove(serverCertificate);
Lines 585-592 CDMInstanceSessionFairPlayStreamingAVFObjC* CDMInstanceFairPlayStreamingAVFObjC: a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec6
585
            continue;
585
            continue;
586
586
587
        auto sessionKeys = sessionInterface->keyIDs();
587
        auto sessionKeys = sessionInterface->keyIDs();
588
        if (anyOf(sessionKeys, [&](const Ref<SharedBuffer>& sessionKey) {
588
        if (anyOf(sessionKeys, [&](const Ref<FragmentedSharedBuffer>& sessionKey) {
589
            return keyIDs.findMatching([&](const Ref<SharedBuffer>& keyID) {
589
            return keyIDs.findMatching([&](const Ref<FragmentedSharedBuffer>& keyID) {
590
                return keyID.get() == sessionKey.get();
590
                return keyID.get() == sessionKey.get();
591
            }) != notFound;
591
            }) != notFound;
592
        }))
592
        }))
Lines 673-679 Keys CDMInstanceSessionFairPlayStreamingAVFObjC::keyIDs() a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec7
673
    return keyIDs;
673
    return keyIDs;
674
}
674
}
675
675
676
void CDMInstanceSessionFairPlayStreamingAVFObjC::requestLicense(LicenseType licenseType, const AtomString& initDataType, Ref<SharedBuffer>&& initData, LicenseCallback&& callback)
676
void CDMInstanceSessionFairPlayStreamingAVFObjC::requestLicense(LicenseType licenseType, const AtomString& initDataType, Ref<FragmentedSharedBuffer>&& initData, LicenseCallback&& callback)
677
{
677
{
678
    if (!isLicenseTypeSupported(licenseType)) {
678
    if (!isLicenseTypeSupported(licenseType)) {
679
        DEBUG_LOG_IF_POSSIBLE(LOGIDENTIFIER, " false, licenseType \"", licenseType, "\" not supported");
679
        DEBUG_LOG_IF_POSSIBLE(LOGIDENTIFIER, " false, licenseType \"", licenseType, "\" not supported");
Lines 709-720 void CDMInstanceSessionFairPlayStreamingAVFObjC::requestLicense(LicenseType lice a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec8
709
    RetainPtr<NSData> initializationData;
709
    RetainPtr<NSData> initializationData;
710
710
711
    if (initDataType == CDMPrivateFairPlayStreaming::sinfName())
711
    if (initDataType == CDMPrivateFairPlayStreaming::sinfName())
712
        initializationData = initData->createNSData();
712
        initializationData = initData->makeContiguous()->createNSData();
713
    else if (initDataType == CDMPrivateFairPlayStreaming::skdName())
713
    else if (initDataType == CDMPrivateFairPlayStreaming::skdName())
714
        identifier = adoptNS([[NSString alloc] initWithData:initData->createNSData().get() encoding:NSUTF8StringEncoding]);
714
        identifier = adoptNS([[NSString alloc] initWithData:initData->makeContiguous()->createNSData().get() encoding:NSUTF8StringEncoding]);
715
#if HAVE(FAIRPLAYSTREAMING_CENC_INITDATA)
715
#if HAVE(FAIRPLAYSTREAMING_CENC_INITDATA)
716
    else if (initDataType == InitDataRegistry::cencName()) {
716
    else if (initDataType == InitDataRegistry::cencName()) {
717
        auto psshString = base64EncodeToString(initData->data(), initData->size());
717
        auto psshString = base64EncodeToString(initData->makeContiguous()->data(), initData->size());
718
        initializationData = [NSJSONSerialization dataWithJSONObject:@{ @"pssh": (NSString*)psshString } options:NSJSONWritingPrettyPrinted error:nil];
718
        initializationData = [NSJSONSerialization dataWithJSONObject:@{ @"pssh": (NSString*)psshString } options:NSJSONWritingPrettyPrinted error:nil];
719
    }
719
    }
720
#endif
720
#endif
Lines 736-742 void CDMInstanceSessionFairPlayStreamingAVFObjC::requestLicense(LicenseType lice a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec9
736
    }
736
    }
737
}
737
}
738
738
739
static bool isEqual(const SharedBuffer& data, const String& value)
739
static bool isEqual(const FragmentedSharedBuffer& data, const String& value)
740
{
740
{
741
    auto arrayBuffer = data.tryCreateArrayBuffer();
741
    auto arrayBuffer = data.tryCreateArrayBuffer();
742
    if (!arrayBuffer)
742
    if (!arrayBuffer)
Lines 754-760 static bool isEqual(const SharedBuffer& data, const String& value) a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec10
754
    return stringOrException.returnValue() == value;
754
    return stringOrException.returnValue() == value;
755
}
755
}
756
756
757
void CDMInstanceSessionFairPlayStreamingAVFObjC::updateLicense(const String&, LicenseType, Ref<SharedBuffer>&& responseData, LicenseUpdateCallback&& callback)
757
void CDMInstanceSessionFairPlayStreamingAVFObjC::updateLicense(const String&, LicenseType, Ref<FragmentedSharedBuffer>&& responseData, LicenseUpdateCallback&& callback)
758
{
758
{
759
    if (!m_expiredSessions.isEmpty() && isEqual(responseData, "acknowledged"_s)) {
759
    if (!m_expiredSessions.isEmpty() && isEqual(responseData, "acknowledged"_s)) {
760
        auto* certificate = m_instance->serverCertificate();
760
        auto* certificate = m_instance->serverCertificate();
Lines 770-776 void CDMInstanceSessionFairPlayStreamingAVFObjC::updateLicense(const String&, Li a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec11
770
        auto expiredSessions = createNSArray(m_expiredSessions, [] (auto& data) {
770
        auto expiredSessions = createNSArray(m_expiredSessions, [] (auto& data) {
771
            return data.get();
771
            return data.get();
772
        });
772
        });
773
        auto appIdentifier = certificate->createNSData();
773
        auto appIdentifier = certificate->makeContiguous()->createNSData();
774
        [PAL::getAVContentKeySessionClass() removePendingExpiredSessionReports:expiredSessions.get() withAppIdentifier:appIdentifier.get() storageDirectoryAtURL:storageURL];
774
        [PAL::getAVContentKeySessionClass() removePendingExpiredSessionReports:expiredSessions.get() withAppIdentifier:appIdentifier.get() storageDirectoryAtURL:storageURL];
775
        callback(false, { }, std::nullopt, std::nullopt, Succeeded);
775
        callback(false, { }, std::nullopt, std::nullopt, Succeeded);
776
        return;
776
        return;
Lines 856-862 void CDMInstanceSessionFairPlayStreamingAVFObjC::updateLicense(const String&, Li a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec12
856
            auto keyID = SharedBuffer::create(WTFMove(*keyIDVector));
856
            auto keyID = SharedBuffer::create(WTFMove(*keyIDVector));
857
            auto foundIndex = m_currentRequest.value().requests.findMatching([&] (auto& request) {
857
            auto foundIndex = m_currentRequest.value().requests.findMatching([&] (auto& request) {
858
                auto keyIDs = keyIDsForRequest(request.get());
858
                auto keyIDs = keyIDsForRequest(request.get());
859
                return keyIDs.findMatching([&](const Ref<SharedBuffer>& id) {
859
                return keyIDs.findMatching([&](const Ref<FragmentedSharedBuffer>& id) {
860
                    return id.get() == keyID.get();
860
                    return id.get() == keyID.get();
861
                }) != notFound;
861
                }) != notFound;
862
            });
862
            });
Lines 888-894 void CDMInstanceSessionFairPlayStreamingAVFObjC::updateLicense(const String&, Li a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec13
888
                if (!payloadVector)
888
                if (!payloadVector)
889
                    return false;
889
                    return false;
890
                auto payloadData = SharedBuffer::create(WTFMove(*payloadVector));
890
                auto payloadData = SharedBuffer::create(WTFMove(*payloadVector));
891
                [request processContentKeyResponse:[PAL::getAVContentKeyResponseClass() contentKeyResponseWithFairPlayStreamingKeyResponseData:payloadData->createNSData().get()]];
891
                [request processContentKeyResponse:[PAL::getAVContentKeyResponseClass() contentKeyResponseWithFairPlayStreamingKeyResponseData:payloadData->makeContiguous()->createNSData().get()]];
892
            }
892
            }
893
            return true;
893
            return true;
894
        };
894
        };
Lines 901-907 void CDMInstanceSessionFairPlayStreamingAVFObjC::updateLicense(const String&, Li a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec14
901
        }
901
        }
902
    } else {
902
    } else {
903
        DEBUG_LOG_IF_POSSIBLE(LOGIDENTIFIER, "'sinf' initData, processing response");
903
        DEBUG_LOG_IF_POSSIBLE(LOGIDENTIFIER, "'sinf' initData, processing response");
904
        [m_currentRequest.value().requests.first() processContentKeyResponse:[PAL::getAVContentKeyResponseClass() contentKeyResponseWithFairPlayStreamingKeyResponseData:responseData->createNSData().get()]];
904
        [m_currentRequest.value().requests.first() processContentKeyResponse:[PAL::getAVContentKeyResponseClass() contentKeyResponseWithFairPlayStreamingKeyResponseData:responseData->makeContiguous()->createNSData().get()]];
905
    }
905
    }
906
906
907
    // FIXME(rdar://problem/35592277): stash the callback and call it once AVContentKeyResponse supports a success callback.
907
    // FIXME(rdar://problem/35592277): stash the callback and call it once AVContentKeyResponse supports a success callback.
Lines 934-940 void CDMInstanceSessionFairPlayStreamingAVFObjC::loadSession(LicenseType license a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec15
934
            return;
934
            return;
935
        }
935
        }
936
936
937
        RetainPtr<NSData> appIdentifier = certificate->createNSData();
937
        RetainPtr<NSData> appIdentifier = certificate->makeContiguous()->createNSData();
938
        KeyStatusVector changedKeys;
938
        KeyStatusVector changedKeys;
939
        for (NSData* expiredSessionData in [PAL::getAVContentKeySessionClass() pendingExpiredSessionReportsWithAppIdentifier:appIdentifier.get() storageDirectoryAtURL:storageURL]) {
939
        for (NSData* expiredSessionData in [PAL::getAVContentKeySessionClass() pendingExpiredSessionReportsWithAppIdentifier:appIdentifier.get() storageDirectoryAtURL:storageURL]) {
940
            static const NSString *PlaybackSessionIdKey = @"PlaybackSessionID";
940
            static const NSString *PlaybackSessionIdKey = @"PlaybackSessionID";
Lines 999-1005 void CDMInstanceSessionFairPlayStreamingAVFObjC::removeSessionData(const String& a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec16
999
            return;
999
            return;
1000
        }
1000
        }
1001
1001
1002
        RetainPtr<NSData> appIdentifier = certificate->createNSData();
1002
        RetainPtr<NSData> appIdentifier = certificate->makeContiguous()->createNSData();
1003
        RetainPtr<NSMutableArray> expiredSessionsArray = adoptNS([[NSMutableArray alloc] init]);
1003
        RetainPtr<NSMutableArray> expiredSessionsArray = adoptNS([[NSMutableArray alloc] init]);
1004
        KeyStatusVector changedKeys;
1004
        KeyStatusVector changedKeys;
1005
        for (NSData* expiredSessionData in [PAL::getAVContentKeySessionClass() pendingExpiredSessionReportsWithAppIdentifier:appIdentifier.get() storageDirectoryAtURL:storageURL]) {
1005
        for (NSData* expiredSessionData in [PAL::getAVContentKeySessionClass() pendingExpiredSessionReportsWithAppIdentifier:appIdentifier.get() storageDirectoryAtURL:storageURL]) {
Lines 1086-1092 void CDMInstanceSessionFairPlayStreamingAVFObjC::didProvideRequest(AVContentKeyR a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec17
1086
1086
1087
    RetainPtr<NSData> appIdentifier;
1087
    RetainPtr<NSData> appIdentifier;
1088
    if (auto* certificate = m_instance->serverCertificate())
1088
    if (auto* certificate = m_instance->serverCertificate())
1089
        appIdentifier = certificate->createNSData();
1089
        appIdentifier = certificate->makeContiguous()->createNSData();
1090
1090
1091
    auto keyIDs = keyIDsForRequest(request);
1091
    auto keyIDs = keyIDsForRequest(request);
1092
    if (keyIDs.isEmpty()) {
1092
    if (keyIDs.isEmpty()) {
Lines 1097-1103 void CDMInstanceSessionFairPlayStreamingAVFObjC::didProvideRequest(AVContentKeyR a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec18
1097
        return;
1097
        return;
1098
    }
1098
    }
1099
1099
1100
    RetainPtr<NSData> contentIdentifier = keyIDs.first()->createNSData();
1100
    RetainPtr<NSData> contentIdentifier = keyIDs.first()->makeContiguous()->createNSData();
1101
    @try {
1101
    @try {
1102
        [request makeStreamingContentKeyRequestDataForApp:appIdentifier.get() contentIdentifier:contentIdentifier.get() options:nil completionHandler:[this, weakThis = WeakPtr { *this }] (NSData *contentKeyRequestData, NSError *error) mutable {
1102
        [request makeStreamingContentKeyRequestDataForApp:appIdentifier.get() contentIdentifier:contentIdentifier.get() options:nil completionHandler:[this, weakThis = WeakPtr { *this }] (NSData *contentKeyRequestData, NSError *error) mutable {
1103
            callOnMainThread([this, weakThis = WTFMove(weakThis), error = retainPtr(error), contentKeyRequestData = retainPtr(contentKeyRequestData)] {
1103
            callOnMainThread([this, weakThis = WTFMove(weakThis), error = retainPtr(error), contentKeyRequestData = retainPtr(contentKeyRequestData)] {
Lines 1153-1161 void CDMInstanceSessionFairPlayStreamingAVFObjC::didProvideRequests(Vector<Retai a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec19
1153
1153
1154
    RetainPtr<NSData> appIdentifier;
1154
    RetainPtr<NSData> appIdentifier;
1155
    if (auto* certificate = m_instance->serverCertificate())
1155
    if (auto* certificate = m_instance->serverCertificate())
1156
        appIdentifier = certificate->createNSData();
1156
        appIdentifier = certificate->makeContiguous()->createNSData();
1157
1157
1158
    using RequestsData = Vector<std::pair<RefPtr<SharedBuffer>, RetainPtr<NSData>>>;
1158
    using RequestsData = Vector<std::pair<RefPtr<FragmentedSharedBuffer>, RetainPtr<NSData>>>;
1159
    struct CallbackAggregator final : public ThreadSafeRefCounted<CallbackAggregator> {
1159
    struct CallbackAggregator final : public ThreadSafeRefCounted<CallbackAggregator> {
1160
        using CallbackFunction = Function<void(RequestsData&&)>;
1160
        using CallbackFunction = Function<void(RequestsData&&)>;
1161
        static RefPtr<CallbackAggregator> create(CallbackFunction&& completionHandler)
1161
        static RefPtr<CallbackAggregator> create(CallbackFunction&& completionHandler)
Lines 1196-1202 void CDMInstanceSessionFairPlayStreamingAVFObjC::didProvideRequests(Vector<Retai a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec20
1196
            auto entry = JSON::Object::create();
1196
            auto entry = JSON::Object::create();
1197
            auto& keyID = requestData.first;
1197
            auto& keyID = requestData.first;
1198
            auto& payload = requestData.second;
1198
            auto& payload = requestData.second;
1199
            entry->setString("keyID", base64EncodeToString(keyID->data(), keyID->size()));
1199
            entry->setString("keyID", base64EncodeToString(keyID->makeContiguous()->data(), keyID->size()));
1200
            entry->setString("payload", base64EncodeToString(payload.get().bytes, payload.get().length));
1200
            entry->setString("payload", base64EncodeToString(payload.get().bytes, payload.get().length));
1201
            requestJSON->pushObject(WTFMove(entry));
1201
            requestJSON->pushObject(WTFMove(entry));
1202
        }
1202
        }
Lines 1211-1218 void CDMInstanceSessionFairPlayStreamingAVFObjC::didProvideRequests(Vector<Retai a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec21
1211
    @try {
1211
    @try {
1212
        for (auto request : m_currentRequest.value().requests) {
1212
        for (auto request : m_currentRequest.value().requests) {
1213
            auto keyIDs = keyIDsForRequest(request.get());
1213
            auto keyIDs = keyIDsForRequest(request.get());
1214
            RefPtr<SharedBuffer> keyID = WTFMove(keyIDs.first());
1214
            RefPtr<FragmentedSharedBuffer> keyID = WTFMove(keyIDs.first());
1215
            auto contentIdentifier = keyID->createNSData();
1215
            auto contentIdentifier = keyID->makeContiguous()->createNSData();
1216
            [request makeStreamingContentKeyRequestDataForApp:appIdentifier.get() contentIdentifier:contentIdentifier.get() options:nil completionHandler:[keyID = WTFMove(keyID), aggregator] (NSData *contentKeyRequestData, NSError *error) mutable {
1216
            [request makeStreamingContentKeyRequestDataForApp:appIdentifier.get() contentIdentifier:contentIdentifier.get() options:nil completionHandler:[keyID = WTFMove(keyID), aggregator] (NSData *contentKeyRequestData, NSError *error) mutable {
1217
                UNUSED_PARAM(error);
1217
                UNUSED_PARAM(error);
1218
                callOnMainThread([keyID = WTFMove(keyID), aggregator = WTFMove(aggregator), contentKeyRequestData = retainPtr(contentKeyRequestData)] () mutable {
1218
                callOnMainThread([keyID = WTFMove(keyID), aggregator = WTFMove(aggregator), contentKeyRequestData = retainPtr(contentKeyRequestData)] () mutable {
Lines 1249-1258 void CDMInstanceSessionFairPlayStreamingAVFObjC::didProvideRenewingRequest(AVCon a/Source/WebCore/platform/graphics/avfoundation/objc/CDMInstanceFairPlayStreamingAVFObjC.mm_sec22
1249
1249
1250
    RetainPtr<NSData> appIdentifier;
1250
    RetainPtr<NSData> appIdentifier;
1251
    if (auto* certificate = m_instance->serverCertificate())
1251
    if (auto* certificate = m_instance->serverCertificate())
1252
        appIdentifier = certificate->createNSData();
1252
        appIdentifier = certificate->makeContiguous()->createNSData();
1253
    auto keyIDs = keyIDsForRequest(m_currentRequest.value());
1253
    auto keyIDs = keyIDsForRequest(m_currentRequest.value());
1254
1254
1255
    RetainPtr<NSData> contentIdentifier = keyIDs.first()->createNSData();
1255
    RetainPtr<NSData> contentIdentifier = keyIDs.first()->makeContiguous()->createNSData();
1256
    @try {
1256
    @try {
1257
        [request makeStreamingContentKeyRequestDataForApp:appIdentifier.get() contentIdentifier:contentIdentifier.get() options:nil completionHandler:[this, weakThis = WeakPtr { *this }] (NSData *contentKeyRequestData, NSError *error) mutable {
1257
        [request makeStreamingContentKeyRequestDataForApp:appIdentifier.get() contentIdentifier:contentIdentifier.get() options:nil completionHandler:[this, weakThis = WeakPtr { *this }] (NSData *contentKeyRequestData, NSError *error) mutable {
1258
            callOnMainThread([this, weakThis = WTFMove(weakThis), error = retainPtr(error), contentKeyRequestData = retainPtr(contentKeyRequestData)] {
1258
            callOnMainThread([this, weakThis = WTFMove(weakThis), error = retainPtr(error), contentKeyRequestData = retainPtr(contentKeyRequestData)] {
- a/Source/WebCore/platform/graphics/avfoundation/objc/ImageDecoderAVFObjC.h -3 / +3 lines
Lines 53-59 class WebCoreDecompressionSession; a/Source/WebCore/platform/graphics/avfoundation/objc/ImageDecoderAVFObjC.h_sec1
53
53
54
class ImageDecoderAVFObjC : public ImageDecoder {
54
class ImageDecoderAVFObjC : public ImageDecoder {
55
public:
55
public:
56
    WEBCORE_EXPORT static RefPtr<ImageDecoderAVFObjC> create(SharedBuffer&, const String& mimeType, AlphaOption, GammaAndColorProfileOption);
56
    WEBCORE_EXPORT static RefPtr<ImageDecoderAVFObjC> create(FragmentedSharedBuffer&, const String& mimeType, AlphaOption, GammaAndColorProfileOption);
57
    virtual ~ImageDecoderAVFObjC();
57
    virtual ~ImageDecoderAVFObjC();
58
58
59
    WEBCORE_EXPORT static bool supportsMediaType(MediaType);
59
    WEBCORE_EXPORT static bool supportsMediaType(MediaType);
Lines 86-92 public: a/Source/WebCore/platform/graphics/avfoundation/objc/ImageDecoderAVFObjC.h_sec2
86
    WEBCORE_EXPORT PlatformImagePtr createFrameImageAtIndex(size_t, SubsamplingLevel = SubsamplingLevel::Default, const DecodingOptions& = DecodingOptions(DecodingMode::Synchronous)) final;
86
    WEBCORE_EXPORT PlatformImagePtr createFrameImageAtIndex(size_t, SubsamplingLevel = SubsamplingLevel::Default, const DecodingOptions& = DecodingOptions(DecodingMode::Synchronous)) final;
87
87
88
    WEBCORE_EXPORT void setExpectedContentSize(long long) final;
88
    WEBCORE_EXPORT void setExpectedContentSize(long long) final;
89
    WEBCORE_EXPORT void setData(SharedBuffer&, bool allDataReceived) final;
89
    WEBCORE_EXPORT void setData(FragmentedSharedBuffer&, bool allDataReceived) final;
90
    bool isAllDataReceived() const final { return m_isAllDataReceived; }
90
    bool isAllDataReceived() const final { return m_isAllDataReceived; }
91
    WEBCORE_EXPORT void clearFrameBufferCache(size_t) final;
91
    WEBCORE_EXPORT void clearFrameBufferCache(size_t) final;
92
92
Lines 94-100 public: a/Source/WebCore/platform/graphics/avfoundation/objc/ImageDecoderAVFObjC.h_sec3
94
    WEBCORE_EXPORT Vector<ImageDecoder::FrameInfo> frameInfos() const;
94
    WEBCORE_EXPORT Vector<ImageDecoder::FrameInfo> frameInfos() const;
95
95
96
private:
96
private:
97
    ImageDecoderAVFObjC(SharedBuffer&, const String& mimeType, AlphaOption, GammaAndColorProfileOption);
97
    ImageDecoderAVFObjC(FragmentedSharedBuffer&, const String& mimeType, AlphaOption, GammaAndColorProfileOption);
98
98
99
    AVAssetTrack *firstEnabledTrack();
99
    AVAssetTrack *firstEnabledTrack();
100
    void readSamples();
100
    void readSamples();
- a/Source/WebCore/platform/graphics/avfoundation/objc/ImageDecoderAVFObjC.mm -5 / +5 lines
Lines 289-295 ImageDecoderAVFObjCSample* toSample(Iterator iter) a/Source/WebCore/platform/graphics/avfoundation/objc/ImageDecoderAVFObjC.mm_sec1
289
289
290
#pragma mark - ImageDecoderAVFObjC
290
#pragma mark - ImageDecoderAVFObjC
291
291
292
RefPtr<ImageDecoderAVFObjC> ImageDecoderAVFObjC::create(SharedBuffer& data, const String& mimeType, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
292
RefPtr<ImageDecoderAVFObjC> ImageDecoderAVFObjC::create(FragmentedSharedBuffer& data, const String& mimeType, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
293
{
293
{
294
    // AVFoundation may not be available at runtime.
294
    // AVFoundation may not be available at runtime.
295
    if (!AVAssetMIMETypeCache::singleton().isAvailable())
295
    if (!AVAssetMIMETypeCache::singleton().isAvailable())
Lines 301-307 RefPtr<ImageDecoderAVFObjC> ImageDecoderAVFObjC::create(SharedBuffer& data, cons a/Source/WebCore/platform/graphics/avfoundation/objc/ImageDecoderAVFObjC.mm_sec2
301
    return adoptRef(*new ImageDecoderAVFObjC(data, mimeType, alphaOption, gammaAndColorProfileOption));
301
    return adoptRef(*new ImageDecoderAVFObjC(data, mimeType, alphaOption, gammaAndColorProfileOption));
302
}
302
}
303
303
304
ImageDecoderAVFObjC::ImageDecoderAVFObjC(SharedBuffer& data, const String& mimeType, AlphaOption, GammaAndColorProfileOption)
304
ImageDecoderAVFObjC::ImageDecoderAVFObjC(FragmentedSharedBuffer& data, const String& mimeType, AlphaOption, GammaAndColorProfileOption)
305
    : ImageDecoder()
305
    : ImageDecoder()
306
    , m_mimeType(mimeType)
306
    , m_mimeType(mimeType)
307
    , m_uti(WebCore::UTIFromMIMEType(mimeType))
307
    , m_uti(WebCore::UTIFromMIMEType(mimeType))
Lines 309-315 ImageDecoderAVFObjC::ImageDecoderAVFObjC(SharedBuffer& data, const String& mimeT a/Source/WebCore/platform/graphics/avfoundation/objc/ImageDecoderAVFObjC.mm_sec3
309
    , m_loader(adoptNS([[WebCoreSharedBufferResourceLoaderDelegate alloc] initWithParent:this]))
309
    , m_loader(adoptNS([[WebCoreSharedBufferResourceLoaderDelegate alloc] initWithParent:this]))
310
    , m_decompressionSession(WebCoreDecompressionSession::createRGB())
310
    , m_decompressionSession(WebCoreDecompressionSession::createRGB())
311
{
311
{
312
    [m_loader updateData:data.createNSData().get() complete:NO];
312
    [m_loader updateData:data.makeContiguous()->createNSData().get() complete:NO];
313
313
314
    [m_asset.get().resourceLoader setDelegate:m_loader.get() queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
314
    [m_asset.get().resourceLoader setDelegate:m_loader.get() queue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
315
    [m_asset loadValuesAsynchronouslyForKeys:@[@"tracks"] completionHandler:[protectedThis = Ref { *this }] () mutable {
315
    [m_asset loadValuesAsynchronouslyForKeys:@[@"tracks"] completionHandler:[protectedThis = Ref { *this }] () mutable {
Lines 641-649 void ImageDecoderAVFObjC::setExpectedContentSize(long long expectedContentSize) a/Source/WebCore/platform/graphics/avfoundation/objc/ImageDecoderAVFObjC.mm_sec4
641
    m_loader.get().expectedContentSize = expectedContentSize;
641
    m_loader.get().expectedContentSize = expectedContentSize;
642
}
642
}
643
643
644
void ImageDecoderAVFObjC::setData(SharedBuffer& data, bool allDataReceived)
644
void ImageDecoderAVFObjC::setData(FragmentedSharedBuffer& data, bool allDataReceived)
645
{
645
{
646
    [m_loader updateData:data.createNSData().get() complete:allDataReceived];
646
    [m_loader updateData:data.makeContiguous()->createNSData().get() complete:allDataReceived];
647
647
648
    if (allDataReceived) {
648
    if (allDataReceived) {
649
        m_isAllDataReceived = true;
649
        m_isAllDataReceived = true;
- a/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.h -2 / +2 lines
Lines 66-72 class InbandMetadataTextTrackPrivateAVF; a/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.h_sec1
66
class MediaPlaybackTarget;
66
class MediaPlaybackTarget;
67
class MediaSelectionGroupAVFObjC;
67
class MediaSelectionGroupAVFObjC;
68
class PixelBufferConformerCV;
68
class PixelBufferConformerCV;
69
class SharedBuffer;
69
class FragmentedSharedBuffer;
70
class VideoLayerManagerObjC;
70
class VideoLayerManagerObjC;
71
class VideoTrackPrivateAVFObjC;
71
class VideoTrackPrivateAVFObjC;
72
class WebCoreAVFResourceLoader;
72
class WebCoreAVFResourceLoader;
Lines 426-432 private: a/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.h_sec2
426
    mutable std::optional<WallTime> m_wallClockAtCachedCurrentTime;
426
    mutable std::optional<WallTime> m_wallClockAtCachedCurrentTime;
427
    mutable int m_timeControlStatusAtCachedCurrentTime { 0 };
427
    mutable int m_timeControlStatusAtCachedCurrentTime { 0 };
428
    mutable double m_requestedRateAtCachedCurrentTime { 0 };
428
    mutable double m_requestedRateAtCachedCurrentTime { 0 };
429
    RefPtr<SharedBuffer> m_keyID;
429
    RefPtr<FragmentedSharedBuffer> m_keyID;
430
    double m_cachedRate { 0 };
430
    double m_cachedRate { 0 };
431
    bool m_requestedPlaying { false };
431
    bool m_requestedPlaying { false };
432
    double m_requestedRate { 1.0 };
432
    double m_requestedRate { 1.0 };
- a/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm -1 / +1 lines
Lines 2792-2798 void MediaPlayerPrivateAVFoundationObjC::attemptToDecryptWithInstance(CDMInstanc a/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm_sec1
2792
    if (!m_keyID || !m_cdmInstance)
2792
    if (!m_keyID || !m_cdmInstance)
2793
        return;
2793
        return;
2794
2794
2795
    auto instanceSession = m_cdmInstance->sessionForKeyIDs(Vector<Ref<SharedBuffer>>::from(*m_keyID));
2795
    auto instanceSession = m_cdmInstance->sessionForKeyIDs(Vector<Ref<FragmentedSharedBuffer>>::from(*m_keyID));
2796
    if (!instanceSession)
2796
    if (!instanceSession)
2797
        return;
2797
        return;
2798
2798
- a/Source/WebCore/platform/graphics/avfoundation/objc/SourceBufferParserAVFObjC.mm -1 / +1 lines
Lines 213-219 SourceBufferParserAVFObjC::~SourceBufferParserAVFObjC() a/Source/WebCore/platform/graphics/avfoundation/objc/SourceBufferParserAVFObjC.mm_sec1
213
void SourceBufferParserAVFObjC::appendData(Segment&& segment, CompletionHandler<void()>&& completionHandler, AppendFlags flags)
213
void SourceBufferParserAVFObjC::appendData(Segment&& segment, CompletionHandler<void()>&& completionHandler, AppendFlags flags)
214
{
214
{
215
    auto sharedBuffer = segment.takeSharedBuffer();
215
    auto sharedBuffer = segment.takeSharedBuffer();
216
    auto nsData = sharedBuffer->createNSData();
216
    auto nsData = sharedBuffer->makeContiguous()->createNSData();
217
    if (m_parserStateWasReset || flags == AppendFlags::Discontinuity)
217
    if (m_parserStateWasReset || flags == AppendFlags::Discontinuity)
218
        [m_parser appendStreamData:nsData.get() withFlags:AVStreamDataParserStreamDataDiscontinuity];
218
        [m_parser appendStreamData:nsData.get() withFlags:AVStreamDataParserStreamDataDiscontinuity];
219
    else
219
    else
- a/Source/WebCore/platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.h -2 / +2 lines
Lines 73-79 class VideoTrackPrivate; a/Source/WebCore/platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.h_sec1
73
class AudioTrackPrivateMediaSourceAVFObjC;
73
class AudioTrackPrivateMediaSourceAVFObjC;
74
class VideoTrackPrivateMediaSourceAVFObjC;
74
class VideoTrackPrivateMediaSourceAVFObjC;
75
class WebCoreDecompressionSession;
75
class WebCoreDecompressionSession;
76
class SharedBuffer;
76
class FragmentedSharedBuffer;
77
77
78
class SourceBufferPrivateAVFObjCErrorClient {
78
class SourceBufferPrivateAVFObjCErrorClient {
79
public:
79
public:
Lines 221-227 private: a/Source/WebCore/platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.h_sec2
221
#endif
221
#endif
222
#if ENABLE(ENCRYPTED_MEDIA) && HAVE(AVCONTENTKEYSESSION)
222
#if ENABLE(ENCRYPTED_MEDIA) && HAVE(AVCONTENTKEYSESSION)
223
    RefPtr<CDMInstanceFairPlayStreamingAVFObjC> m_cdmInstance;
223
    RefPtr<CDMInstanceFairPlayStreamingAVFObjC> m_cdmInstance;
224
    Vector<Ref<SharedBuffer>> m_keyIDs;
224
    Vector<Ref<FragmentedSharedBuffer>> m_keyIDs;
225
#endif
225
#endif
226
226
227
    std::optional<FloatSize> m_cachedSize;
227
    std::optional<FloatSize> m_cachedSize;
- a/Source/WebCore/platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.h -2 / +2 lines
Lines 43-49 class MediaPlayerPrivateAVFoundationObjC; a/Source/WebCore/platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.h_sec1
43
class PlatformResourceMediaLoader;
43
class PlatformResourceMediaLoader;
44
class ResourceError;
44
class ResourceError;
45
class ResourceResponse;
45
class ResourceResponse;
46
class SharedBuffer;
46
class FragmentedSharedBuffer;
47
47
48
class WebCoreAVFResourceLoader : public RefCounted<WebCoreAVFResourceLoader> {
48
class WebCoreAVFResourceLoader : public RefCounted<WebCoreAVFResourceLoader> {
49
    WTF_MAKE_NONCOPYABLE(WebCoreAVFResourceLoader); WTF_MAKE_FAST_ALLOCATED;
49
    WTF_MAKE_NONCOPYABLE(WebCoreAVFResourceLoader); WTF_MAKE_FAST_ALLOCATED;
Lines 65-71 private: a/Source/WebCore/platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.h_sec2
65
    void responseReceived(const ResourceResponse&);
65
    void responseReceived(const ResourceResponse&);
66
    void loadFailed(const ResourceError&);
66
    void loadFailed(const ResourceError&);
67
    void loadFinished();
67
    void loadFinished();
68
    void newDataStoredInSharedBuffer(SharedBuffer&);
68
    void newDataStoredInSharedBuffer(const FragmentedSharedBuffer&);
69
69
70
    MediaPlayerPrivateAVFoundationObjC* m_parent;
70
    MediaPlayerPrivateAVFoundationObjC* m_parent;
71
    RetainPtr<AVAssetResourceLoadingRequest> m_avRequest;
71
    RetainPtr<AVAssetResourceLoadingRequest> m_avRequest;
- a/Source/WebCore/platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm -9 / +6 lines
Lines 156-169 private: a/Source/WebCore/platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm_sec1
156
    void redirectReceived(PlatformMediaResource&, ResourceRequest&& request, const ResourceResponse&, CompletionHandler<void(ResourceRequest&&)>&& completionHandler) final { completionHandler(WTFMove(request)); }
156
    void redirectReceived(PlatformMediaResource&, ResourceRequest&& request, const ResourceResponse&, CompletionHandler<void(ResourceRequest&&)>&& completionHandler) final { completionHandler(WTFMove(request)); }
157
    bool shouldCacheResponse(PlatformMediaResource&, const ResourceResponse&) final { return false; }
157
    bool shouldCacheResponse(PlatformMediaResource&, const ResourceResponse&) final { return false; }
158
    void dataSent(PlatformMediaResource&, unsigned long long, unsigned long long) final { }
158
    void dataSent(PlatformMediaResource&, unsigned long long, unsigned long long) final { }
159
    void dataReceived(PlatformMediaResource&, Ref<SharedBuffer>&&) final;
159
    void dataReceived(PlatformMediaResource&, Ref<FragmentedSharedBuffer>&&) final;
160
    void accessControlCheckFailed(PlatformMediaResource&, const ResourceError& error) final { loadFailed(error); }
160
    void accessControlCheckFailed(PlatformMediaResource&, const ResourceError& error) final { loadFailed(error); }
161
    void loadFailed(PlatformMediaResource&, const ResourceError& error) final { loadFailed(error); }
161
    void loadFailed(PlatformMediaResource&, const ResourceError& error) final { loadFailed(error); }
162
    void loadFinished(PlatformMediaResource&, const NetworkLoadMetrics&) final { loadFinished(); }
162
    void loadFinished(PlatformMediaResource&, const NetworkLoadMetrics&) final { loadFinished(); }
163
163
164
    WebCoreAVFResourceLoader& m_parent;
164
    WebCoreAVFResourceLoader& m_parent;
165
    RefPtr<PlatformMediaResource> m_resource;
165
    RefPtr<PlatformMediaResource> m_resource;
166
    RefPtr<SharedBuffer> m_buffer;
166
    SharedBufferBuilder m_buffer;
167
};
167
};
168
168
169
WeakPtr<PlatformResourceMediaLoader> PlatformResourceMediaLoader::create(WebCoreAVFResourceLoader& parent, PlatformMediaResourceLoader& loader, ResourceRequest&& request)
169
WeakPtr<PlatformResourceMediaLoader> PlatformResourceMediaLoader::create(WebCoreAVFResourceLoader& parent, PlatformMediaResourceLoader& loader, ResourceRequest&& request)
Lines 211-223 void PlatformResourceMediaLoader::loadFinished() a/Source/WebCore/platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm_sec2
211
    m_parent.loadFinished();
211
    m_parent.loadFinished();
212
}
212
}
213
213
214
void PlatformResourceMediaLoader::dataReceived(PlatformMediaResource&, Ref<SharedBuffer>&& buffer)
214
void PlatformResourceMediaLoader::dataReceived(PlatformMediaResource&, Ref<FragmentedSharedBuffer>&& buffer)
215
{
215
{
216
    if (!m_buffer)
216
    m_buffer.append(WTFMove(buffer));
217
        m_buffer = WTFMove(buffer);
217
    m_parent.newDataStoredInSharedBuffer(*m_buffer.get());
218
    else
219
        m_buffer->append(WTFMove(buffer));
220
    m_parent.newDataStoredInSharedBuffer(*m_buffer);
221
}
218
}
222
219
223
class DataURLResourceMediaLoader : public CanMakeWeakPtr<DataURLResourceMediaLoader> {
220
class DataURLResourceMediaLoader : public CanMakeWeakPtr<DataURLResourceMediaLoader> {
Lines 388-394 void WebCoreAVFResourceLoader::loadFinished() a/Source/WebCore/platform/graphics/avfoundation/objc/WebCoreAVFResourceLoader.mm_sec3
388
    stopLoading();
385
    stopLoading();
389
}
386
}
390
387
391
void WebCoreAVFResourceLoader::newDataStoredInSharedBuffer(SharedBuffer& data)
388
void WebCoreAVFResourceLoader::newDataStoredInSharedBuffer(const FragmentedSharedBuffer& data)
392
{
389
{
393
    AVAssetResourceLoadingDataRequest* dataRequest = [m_avRequest dataRequest];
390
    AVAssetResourceLoadingDataRequest* dataRequest = [m_avRequest dataRequest];
394
    if (!dataRequest)
391
    if (!dataRequest)
- a/Source/WebCore/platform/graphics/cairo/FontCustomPlatformData.h -2 / +3 lines
Lines 31-40 typedef struct FT_FaceRec_* FT_Face; a/Source/WebCore/platform/graphics/cairo/FontCustomPlatformData.h_sec1
31
31
32
namespace WebCore {
32
namespace WebCore {
33
33
34
class SharedBuffer;
34
class FontCreationContext;
35
class FontCreationContext;
35
class FontDescription;
36
class FontDescription;
36
class FontPlatformData;
37
class FontPlatformData;
37
class SharedBuffer;
38
class FragmentedSharedBuffer;
38
struct FontSelectionSpecifiedCapabilities;
39
struct FontSelectionSpecifiedCapabilities;
39
struct FontVariantSettings;
40
struct FontVariantSettings;
40
41
Lines 45-51 struct FontCustomPlatformData { a/Source/WebCore/platform/graphics/cairo/FontCustomPlatformData.h_sec2
45
    WTF_MAKE_FAST_ALLOCATED;
46
    WTF_MAKE_FAST_ALLOCATED;
46
    WTF_MAKE_NONCOPYABLE(FontCustomPlatformData);
47
    WTF_MAKE_NONCOPYABLE(FontCustomPlatformData);
47
public:
48
public:
48
    FontCustomPlatformData(FT_Face, SharedBuffer&);
49
    FontCustomPlatformData(FT_Face, FragmentedSharedBuffer&);
49
    ~FontCustomPlatformData() = default;
50
    ~FontCustomPlatformData() = default;
50
    FontPlatformData fontPlatformData(const FontDescription&, bool bold, bool italic, const FontCreationContext&);
51
    FontPlatformData fontPlatformData(const FontDescription&, bool bold, bool italic, const FontCreationContext&);
51
    static bool supportsFormat(const String&);
52
    static bool supportsFormat(const String&);
- a/Source/WebCore/platform/graphics/cg/ImageDecoderCG.cpp -12 / +13 lines
Lines 244-259 size_t sharedBufferGetBytesAtPosition(void* info, void* buffer, off_t position, a/Source/WebCore/platform/graphics/cg/ImageDecoderCG.cpp_sec1
244
244
245
void sharedBufferRelease(void* info)
245
void sharedBufferRelease(void* info)
246
{
246
{
247
    SharedBuffer* sharedBuffer = static_cast<SharedBuffer*>(info);
247
    FragmentedSharedBuffer* sharedBuffer = static_cast<FragmentedSharedBuffer*>(info);
248
    sharedBuffer->deref();
248
    sharedBuffer->deref();
249
}
249
}
250
#endif
250
#endif
251
251
252
ImageDecoderCG::ImageDecoderCG(SharedBuffer& data, AlphaOption, GammaAndColorProfileOption)
252
ImageDecoderCG::ImageDecoderCG(FragmentedSharedBuffer& data, AlphaOption, GammaAndColorProfileOption)
253
{
253
{
254
    RetainPtr<CFStringRef> utiHint;
254
    RetainPtr<CFStringRef> utiHint;
255
    if (data.size() >= 32)
255
    if (data.size() >= 32)
256
        utiHint = adoptCF(CGImageSourceGetTypeWithData(data.createCFData().get(), nullptr, nullptr));
256
        utiHint = adoptCF(CGImageSourceGetTypeWithData(data.makeContiguous()->createCFData().get(), nullptr, nullptr));
257
    
257
    
258
    if (utiHint) {
258
    if (utiHint) {
259
        const void* key = kCGImageSourceTypeIdentifierHint;
259
        const void* key = kCGImageSourceTypeIdentifierHint;
Lines 562-584 PlatformImagePtr ImageDecoderCG::createFrameImageAtIndex(size_t index, Subsampli a/Source/WebCore/platform/graphics/cg/ImageDecoderCG.cpp_sec2
562
    return maskedImage ? maskedImage : image;
562
    return maskedImage ? maskedImage : image;
563
}
563
}
564
564
565
void ImageDecoderCG::setData(SharedBuffer& data, bool allDataReceived)
565
void ImageDecoderCG::setData(FragmentedSharedBuffer& data, bool allDataReceived)
566
{
566
{
567
    m_isAllDataReceived = allDataReceived;
567
    m_isAllDataReceived = allDataReceived;
568
568
569
#if PLATFORM(COCOA)
569
#if PLATFORM(COCOA)
570
    // On Mac the NSData inside the SharedBuffer can be secretly appended to without the SharedBuffer's knowledge.
570
    // On Mac the NSData inside the FragmentedSharedBuffer can be secretly appended to without the FragmentedSharedBuffer's knowledge.
571
    // We use SharedBuffer's ability to wrap itself inside CFData to get around this, ensuring that ImageIO is
571
    // We use FragmentedSharedBuffer's ability to wrap itself inside CFData to get around this, ensuring that ImageIO is
572
    // really looking at the SharedBuffer.
572
    // really looking at the FragmentedSharedBuffer.
573
    CGImageSourceUpdateData(m_nativeDecoder.get(), data.createCFData().get(), allDataReceived);
573
    CGImageSourceUpdateData(m_nativeDecoder.get(), data.makeContiguous()->createCFData().get(), allDataReceived);
574
#else
574
#else
575
    // Create a CGDataProvider to wrap the SharedBuffer.
575
    // Create a CGDataProvider to wrap the FragmentedSharedBuffer.
576
    data.ref();
576
    auto contiguousData = data.makeContiguous();
577
    // We use the GetBytesAtPosition callback rather than the GetBytePointer one because SharedBuffer
577
    contiguousData.get().ref();
578
    // We use the GetBytesAtPosition callback rather than the GetBytePointer one because FragmentedSharedBuffer
578
    // does not provide a way to lock down the byte pointer and guarantee that it won't move, which
579
    // does not provide a way to lock down the byte pointer and guarantee that it won't move, which
579
    // is a requirement for using the GetBytePointer callback.
580
    // is a requirement for using the GetBytePointer callback.
580
    CGDataProviderDirectCallbacks providerCallbacks = { 0, 0, 0, sharedBufferGetBytesAtPosition, sharedBufferRelease };
581
    CGDataProviderDirectCallbacks providerCallbacks = { 0, 0, 0, sharedBufferGetBytesAtPosition, sharedBufferRelease };
581
    RetainPtr<CGDataProviderRef> dataProvider = adoptCF(CGDataProviderCreateDirect(&data, data.size(), &providerCallbacks));
582
    RetainPtr<CGDataProviderRef> dataProvider = adoptCF(CGDataProviderCreateDirect(contiguousData.ptr(), data.size(), &providerCallbacks));
582
    CGImageSourceUpdateDataProvider(m_nativeDecoder.get(), dataProvider.get(), allDataReceived);
583
    CGImageSourceUpdateDataProvider(m_nativeDecoder.get(), dataProvider.get(), allDataReceived);
583
#endif
584
#endif
584
}
585
}
- a/Source/WebCore/platform/graphics/cg/ImageDecoderCG.h -3 / +3 lines
Lines 32-40 namespace WebCore { a/Source/WebCore/platform/graphics/cg/ImageDecoderCG.h_sec1
32
class ImageDecoderCG final : public ImageDecoder {
32
class ImageDecoderCG final : public ImageDecoder {
33
    WTF_MAKE_FAST_ALLOCATED;
33
    WTF_MAKE_FAST_ALLOCATED;
34
public:
34
public:
35
    ImageDecoderCG(SharedBuffer& data, AlphaOption, GammaAndColorProfileOption);
35
    ImageDecoderCG(FragmentedSharedBuffer& data, AlphaOption, GammaAndColorProfileOption);
36
36
37
    static Ref<ImageDecoderCG> create(SharedBuffer& data, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
37
    static Ref<ImageDecoderCG> create(FragmentedSharedBuffer& data, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
38
    {
38
    {
39
        return adoptRef(*new ImageDecoderCG(data, alphaOption, gammaAndColorProfileOption));
39
        return adoptRef(*new ImageDecoderCG(data, alphaOption, gammaAndColorProfileOption));
40
    }
40
    }
Lines 64-70 public: a/Source/WebCore/platform/graphics/cg/ImageDecoderCG.h_sec2
64
64
65
    PlatformImagePtr createFrameImageAtIndex(size_t, SubsamplingLevel = SubsamplingLevel::Default, const DecodingOptions& = DecodingOptions(DecodingMode::Synchronous)) final;
65
    PlatformImagePtr createFrameImageAtIndex(size_t, SubsamplingLevel = SubsamplingLevel::Default, const DecodingOptions& = DecodingOptions(DecodingMode::Synchronous)) final;
66
66
67
    void setData(SharedBuffer&, bool allDataReceived) final;
67
    void setData(FragmentedSharedBuffer&, bool allDataReceived) final;
68
    bool isAllDataReceived() const final { return m_isAllDataReceived; }
68
    bool isAllDataReceived() const final { return m_isAllDataReceived; }
69
    void clearFrameBufferCache(size_t) final { }
69
    void clearFrameBufferCache(size_t) final { }
70
70
- a/Source/WebCore/platform/graphics/cg/PDFDocumentImage.cpp -1 / +1 lines
Lines 319-325 void PDFDocumentImage::destroyDecodedData(bool) a/Source/WebCore/platform/graphics/cg/PDFDocumentImage.cpp_sec1
319
319
320
void PDFDocumentImage::createPDFDocument()
320
void PDFDocumentImage::createPDFDocument()
321
{
321
{
322
    RetainPtr<CGDataProviderRef> dataProvider = adoptCF(CGDataProviderCreateWithCFData(data()->createCFData().get()));
322
    RetainPtr<CGDataProviderRef> dataProvider = adoptCF(CGDataProviderCreateWithCFData(data()->makeContiguous()->createCFData().get()));
323
    m_document = adoptCF(CGPDFDocumentCreateWithProvider(dataProvider.get()));
323
    m_document = adoptCF(CGPDFDocumentCreateWithProvider(dataProvider.get()));
324
}
324
}
325
325
- a/Source/WebCore/platform/graphics/cocoa/SourceBufferParserWebM.cpp -10 / +7 lines
Lines 365-373 public: a/Source/WebCore/platform/graphics/cocoa/SourceBufferParserWebM.cpp_sec1
365
        return Status(Status::kWouldBlock);
365
        return Status(Status::kWouldBlock);
366
    }
366
    }
367
367
368
    static void FreeDataSegment(void* refcon, void*, size_t)
368
    static void FreeSharedBuffer(void* refcon, void*, size_t)
369
    {
369
    {
370
        auto* buffer = reinterpret_cast<SharedBuffer::DataSegment*>(refcon);
370
        auto* buffer = reinterpret_cast<SharedBuffer*>(refcon);
371
        buffer->deref();
371
        buffer->deref();
372
    }
372
    }
373
373
Lines 408-418 public: a/Source/WebCore/platform/graphics/cocoa/SourceBufferParserWebM.cpp_sec2
408
                lastRead = readResult.value();
408
                lastRead = readResult.value();
409
                destinationOffset = 0;
409
                destinationOffset = 0;
410
            } else {
410
            } else {
411
                ASSERT(sharedBuffer->hasOneSegment(), "Can only deal with sharedBuffer containing a single DataSegment");
412
                // A SharedBuffer doesn't have thread-safe refcounting, as such we must keep a reference to the DataSegment instead.
413
                // TODO: could we only create a new CMBlockBuffer if the backend memory changed since the previous one?
411
                // TODO: could we only create a new CMBlockBuffer if the backend memory changed since the previous one?
414
                auto firstSegment = sharedBuffer->begin()->segment;
412
                size_t canRead = std::min<size_t>(numToRead, sharedBuffer->size() - m_positionWithinSegment);
415
                size_t canRead = std::min<size_t>(numToRead, firstSegment->size() - m_positionWithinSegment);
416
                // From CMBlockBufferCustomBlockSource documentation:
413
                // From CMBlockBufferCustomBlockSource documentation:
417
                // Note that for 64-bit architectures, this struct contains misaligned function pointers.
414
                // Note that for 64-bit architectures, this struct contains misaligned function pointers.
418
                // To avoid link-time issues, it is recommended that clients fill CMBlockBufferCustomBlockSource's function pointer fields
415
                // To avoid link-time issues, it is recommended that clients fill CMBlockBufferCustomBlockSource's function pointer fields
Lines 420-429 public: a/Source/WebCore/platform/graphics/cocoa/SourceBufferParserWebM.cpp_sec3
420
                CMBlockBufferCustomBlockSource allocator;
417
                CMBlockBufferCustomBlockSource allocator;
421
                allocator.version = 0;
418
                allocator.version = 0;
422
                allocator.AllocateBlock = nullptr;
419
                allocator.AllocateBlock = nullptr;
423
                allocator.FreeBlock = FreeDataSegment;
420
                allocator.FreeBlock = FreeSharedBuffer;
424
                allocator.refCon = firstSegment.ptr();
421
                allocator.refCon = sharedBuffer.get();
425
                firstSegment->ref();
422
                sharedBuffer->ref();
426
                auto err = PAL::CMBlockBufferCreateWithMemoryBlock(nullptr, static_cast<void*>(const_cast<uint8_t*>(firstSegment->data())), firstSegment->size(), nullptr, &allocator, m_positionWithinSegment, canRead, 0, &rawBlockBuffer);
423
                auto err = PAL::CMBlockBufferCreateWithMemoryBlock(nullptr, static_cast<void*>(const_cast<uint8_t*>(sharedBuffer->data())), sharedBuffer->size(), nullptr, &allocator, m_positionWithinSegment, canRead, 0, &rawBlockBuffer);
427
                if (err != kCMBlockBufferNoErr)
424
                if (err != kCMBlockBufferNoErr)
428
                    return Status(Status::kNotEnoughMemory);
425
                    return Status(Status::kNotEnoughMemory);
429
                lastRead = canRead;
426
                lastRead = canRead;
- a/Source/WebCore/platform/graphics/displaylists/DisplayListItemBuffer.cpp -1 / +1 lines
Lines 737-743 DidChangeItemBuffer ItemBuffer::swapWritableBufferIfNeeded(size_t numberOfBytes) a/Source/WebCore/platform/graphics/displaylists/DisplayListItemBuffer.cpp_sec1
737
void ItemBuffer::append(const DisplayListItem& temporaryItem)
737
void ItemBuffer::append(const DisplayListItem& temporaryItem)
738
{
738
{
739
    auto requiredSizeForItem = m_writingClient->requiredSizeForItem(temporaryItem);
739
    auto requiredSizeForItem = m_writingClient->requiredSizeForItem(temporaryItem);
740
    RefPtr<SharedBuffer> outOfLineItem;
740
    RefPtr<FragmentedSharedBuffer> outOfLineItem;
741
    if (!requiredSizeForItem) {
741
    if (!requiredSizeForItem) {
742
        outOfLineItem = m_writingClient->encodeItemOutOfLine(temporaryItem);
742
        outOfLineItem = m_writingClient->encodeItemOutOfLine(temporaryItem);
743
        if (!outOfLineItem)
743
        if (!outOfLineItem)
- a/Source/WebCore/platform/graphics/displaylists/DisplayListItemBuffer.h -2 / +2 lines
Lines 102-108 public: a/Source/WebCore/platform/graphics/displaylists/DisplayListItemBuffer.h_sec1
102
        return std::nullopt;
102
        return std::nullopt;
103
    }
103
    }
104
104
105
    virtual RefPtr<SharedBuffer> encodeItemOutOfLine(const DisplayListItem&) const
105
    virtual RefPtr<FragmentedSharedBuffer> encodeItemOutOfLine(const DisplayListItem&) const
106
    {
106
    {
107
        return nullptr;
107
        return nullptr;
108
    }
108
    }
Lines 168-174 public: a/Source/WebCore/platform/graphics/displaylists/DisplayListItemBuffer.h_sec2
168
    // with padding between each item to ensure that all items are aligned to 8 bytes.
168
    // with padding between each item to ensure that all items are aligned to 8 bytes.
169
    //
169
    //
170
    // If a writing client is present and requires custom encoding for the given item type T, the
170
    // If a writing client is present and requires custom encoding for the given item type T, the
171
    // item buffer will ask the client for an opaque SharedBuffer containing encoded data for the
171
    // item buffer will ask the client for an opaque FragmentedSharedBuffer containing encoded data for the
172
    // item. This encoded data is then appended to the item buffer, with padding to ensure that
172
    // item. This encoded data is then appended to the item buffer, with padding to ensure that
173
    // the start and end of this data are aligned to 8 bytes, if necessary. When consuming encoded
173
    // the start and end of this data are aligned to 8 bytes, if necessary. When consuming encoded
174
    // item data, a corresponding ItemBufferReadingClient will be required to convert this encoded
174
    // item data, a corresponding ItemBufferReadingClient will be required to convert this encoded
- a/Source/WebCore/platform/graphics/freetype/FontCustomPlatformDataFreeType.cpp -2 / +2 lines
Lines 38-49 namespace WebCore { a/Source/WebCore/platform/graphics/freetype/FontCustomPlatformDataFreeType.cpp_sec1
38
38
39
static void releaseCustomFontData(void* data)
39
static void releaseCustomFontData(void* data)
40
{
40
{
41
    static_cast<SharedBuffer*>(data)->deref();
41
    static_cast<FragmentedSharedBuffer*>(data)->deref();
42
}
42
}
43
43
44
static cairo_user_data_key_t freeTypeFaceKey;
44
static cairo_user_data_key_t freeTypeFaceKey;
45
45
46
FontCustomPlatformData::FontCustomPlatformData(FT_Face freeTypeFace, SharedBuffer& buffer)
46
FontCustomPlatformData::FontCustomPlatformData(FT_Face freeTypeFace, FragmentedSharedBuffer& buffer)
47
    : m_fontFace(adoptRef(cairo_ft_font_face_create_for_ft_face(freeTypeFace, FT_LOAD_DEFAULT)))
47
    : m_fontFace(adoptRef(cairo_ft_font_face_create_for_ft_face(freeTypeFace, FT_LOAD_DEFAULT)))
48
{
48
{
49
    buffer.ref(); // This is balanced by the buffer->deref() in releaseCustomFontData.
49
    buffer.ref(); // This is balanced by the buffer->deref() in releaseCustomFontData.
- a/Source/WebCore/platform/graphics/gstreamer/ImageDecoderGStreamer.cpp -5 / +6 lines
Lines 81-92 ImageDecoderGStreamerSample* toSample(Iterator iter) a/Source/WebCore/platform/graphics/gstreamer/ImageDecoderGStreamer.cpp_sec1
81
    return (ImageDecoderGStreamerSample*)iter->second.get();
81
    return (ImageDecoderGStreamerSample*)iter->second.get();
82
}
82
}
83
83
84
RefPtr<ImageDecoderGStreamer> ImageDecoderGStreamer::create(SharedBuffer& data, const String& mimeType, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
84
RefPtr<ImageDecoderGStreamer> ImageDecoderGStreamer::create(FragmentedSharedBuffer& data, const String& mimeType, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
85
{
85
{
86
    return adoptRef(*new ImageDecoderGStreamer(data, mimeType, alphaOption, gammaAndColorProfileOption));
86
    return adoptRef(*new ImageDecoderGStreamer(data, mimeType, alphaOption, gammaAndColorProfileOption));
87
}
87
}
88
88
89
ImageDecoderGStreamer::ImageDecoderGStreamer(SharedBuffer& data, const String& mimeType, AlphaOption, GammaAndColorProfileOption)
89
ImageDecoderGStreamer::ImageDecoderGStreamer(FragmentedSharedBuffer& data, const String& mimeType, AlphaOption, GammaAndColorProfileOption)
90
    : m_mimeType(mimeType)
90
    : m_mimeType(mimeType)
91
{
91
{
92
    static std::once_flag onceFlag;
92
    static std::once_flag onceFlag;
Lines 199-205 PlatformImagePtr ImageDecoderGStreamer::createFrameImageAtIndex(size_t index, Su a/Source/WebCore/platform/graphics/gstreamer/ImageDecoderGStreamer.cpp_sec2
199
    return nullptr;
199
    return nullptr;
200
}
200
}
201
201
202
void ImageDecoderGStreamer::setData(SharedBuffer& data, bool)
202
void ImageDecoderGStreamer::setData(FragmentedSharedBuffer& data, bool)
203
{
203
{
204
    pushEncodedData(data);
204
    pushEncodedData(data);
205
}
205
}
Lines 426-435 EncodedDataStatus ImageDecoderGStreamer::InnerDecoder::encodedDataStatus() const a/Source/WebCore/platform/graphics/gstreamer/ImageDecoderGStreamer.cpp_sec3
426
    return EncodedDataStatus::Unknown;
426
    return EncodedDataStatus::Unknown;
427
}
427
}
428
428
429
void ImageDecoderGStreamer::pushEncodedData(const SharedBuffer& buffer)
429
void ImageDecoderGStreamer::pushEncodedData(const FragmentedSharedBuffer& buffer)
430
{
430
{
431
    auto contiguousBuffer = buffer.makeContiguous();
431
    m_eos = false;
432
    m_eos = false;
432
    auto thread = Thread::create("ImageDecoderGStreamer", [this, data = buffer.data(), size = buffer.size()] {
433
    auto thread = Thread::create("ImageDecoderGStreamer", [this, data = contiguousBuffer->data(), size = buffer.size()] {
433
        m_innerDecoder = ImageDecoderGStreamer::InnerDecoder::create(*this, data, size);
434
        m_innerDecoder = ImageDecoderGStreamer::InnerDecoder::create(*this, data, size);
434
        m_innerDecoder->run();
435
        m_innerDecoder->run();
435
    }, ThreadType::Graphics);
436
    }, ThreadType::Graphics);
- a/Source/WebCore/platform/graphics/gstreamer/ImageDecoderGStreamer.h -4 / +4 lines
Lines 41-48 class ImageDecoderGStreamer final : public ImageDecoder { a/Source/WebCore/platform/graphics/gstreamer/ImageDecoderGStreamer.h_sec1
41
    WTF_MAKE_FAST_ALLOCATED;
41
    WTF_MAKE_FAST_ALLOCATED;
42
    WTF_MAKE_NONCOPYABLE(ImageDecoderGStreamer);
42
    WTF_MAKE_NONCOPYABLE(ImageDecoderGStreamer);
43
public:
43
public:
44
    static RefPtr<ImageDecoderGStreamer> create(SharedBuffer&, const String& mimeType, AlphaOption, GammaAndColorProfileOption);
44
    static RefPtr<ImageDecoderGStreamer> create(FragmentedSharedBuffer&, const String& mimeType, AlphaOption, GammaAndColorProfileOption);
45
    ImageDecoderGStreamer(SharedBuffer&, const String& mimeType, AlphaOption, GammaAndColorProfileOption);
45
    ImageDecoderGStreamer(FragmentedSharedBuffer&, const String& mimeType, AlphaOption, GammaAndColorProfileOption);
46
    virtual ~ImageDecoderGStreamer() = default;
46
    virtual ~ImageDecoderGStreamer() = default;
47
47
48
    static bool supportsMediaType(MediaType type) { return type == MediaType::Video; }
48
    static bool supportsMediaType(MediaType type) { return type == MediaType::Video; }
Lines 72-78 public: a/Source/WebCore/platform/graphics/gstreamer/ImageDecoderGStreamer.h_sec2
72
    PlatformImagePtr createFrameImageAtIndex(size_t, SubsamplingLevel = SubsamplingLevel::Default, const DecodingOptions& = DecodingOptions(DecodingMode::Synchronous)) final;
72
    PlatformImagePtr createFrameImageAtIndex(size_t, SubsamplingLevel = SubsamplingLevel::Default, const DecodingOptions& = DecodingOptions(DecodingMode::Synchronous)) final;
73
73
74
    void setExpectedContentSize(long long) final { }
74
    void setExpectedContentSize(long long) final { }
75
    void setData(SharedBuffer&, bool allDataReceived) final;
75
    void setData(FragmentedSharedBuffer&, bool allDataReceived) final;
76
    bool isAllDataReceived() const final { return m_eos; }
76
    bool isAllDataReceived() const final { return m_eos; }
77
    void clearFrameBufferCache(size_t) final;
77
    void clearFrameBufferCache(size_t) final;
78
78
Lines 122-128 private: a/Source/WebCore/platform/graphics/gstreamer/ImageDecoderGStreamer.h_sec3
122
    };
122
    };
123
123
124
    void handleSample(GRefPtr<GstSample>&&);
124
    void handleSample(GRefPtr<GstSample>&&);
125
    void pushEncodedData(const SharedBuffer&);
125
    void pushEncodedData(const FragmentedSharedBuffer&);
126
126
127
    const ImageDecoderGStreamerSample* sampleAtIndex(size_t) const;
127
    const ImageDecoderGStreamerSample* sampleAtIndex(size_t) const;
128
128
- a/Source/WebCore/platform/graphics/gstreamer/MediaPlayerPrivateGStreamer.cpp -1 / +1 lines
Lines 3692-3698 void MediaPlayerPrivateGStreamer::initializationDataEncountered(InitData&& initD a/Source/WebCore/platform/graphics/gstreamer/MediaPlayerPrivateGStreamer.cpp_sec1
3692
3692
3693
        GST_DEBUG("scheduling initializationDataEncountered %s event of size %zu", initData.payloadContainerType().utf8().data(),
3693
        GST_DEBUG("scheduling initializationDataEncountered %s event of size %zu", initData.payloadContainerType().utf8().data(),
3694
            initData.payload()->size());
3694
            initData.payload()->size());
3695
        GST_MEMDUMP("init datas", reinterpret_cast<const uint8_t*>(initData.payload()->data()), initData.payload()->size());
3695
        GST_MEMDUMP("init datas", reinterpret_cast<const uint8_t*>(initData.payload()->makeContiguous()->data()), initData.payload()->size());
3696
        weakThis->m_player->initializationDataEncountered(initData.payloadContainerType(), initData.payload()->tryCreateArrayBuffer());
3696
        weakThis->m_player->initializationDataEncountered(initData.payloadContainerType(), initData.payload()->tryCreateArrayBuffer());
3697
    });
3697
    });
3698
}
3698
}
- a/Source/WebCore/platform/graphics/gstreamer/WebKitWebSourceGStreamer.cpp -2 / +2 lines
Lines 71-77 private: a/Source/WebCore/platform/graphics/gstreamer/WebKitWebSourceGStreamer.cpp_sec1
71
71
72
    // PlatformMediaResourceClient virtual methods.
72
    // PlatformMediaResourceClient virtual methods.
73
    void responseReceived(PlatformMediaResource&, const ResourceResponse&, CompletionHandler<void(ShouldContinuePolicyCheck)>&&) override;
73
    void responseReceived(PlatformMediaResource&, const ResourceResponse&, CompletionHandler<void(ShouldContinuePolicyCheck)>&&) override;
74
    void dataReceived(PlatformMediaResource&, Ref<SharedBuffer>&&) override;
74
    void dataReceived(PlatformMediaResource&, Ref<FragmentedSharedBuffer>&&) override;
75
    void accessControlCheckFailed(PlatformMediaResource&, const ResourceError&) override;
75
    void accessControlCheckFailed(PlatformMediaResource&, const ResourceError&) override;
76
    void loadFailed(PlatformMediaResource&, const ResourceError&) override;
76
    void loadFailed(PlatformMediaResource&, const ResourceError&) override;
77
    void loadFinished(PlatformMediaResource&, const NetworkLoadMetrics&) override;
77
    void loadFinished(PlatformMediaResource&, const NetworkLoadMetrics&) override;
Lines 1093-1099 void CachedResourceStreamingClient::responseReceived(PlatformMediaResource&, con a/Source/WebCore/platform/graphics/gstreamer/WebKitWebSourceGStreamer.cpp_sec2
1093
    completionHandler(ShouldContinuePolicyCheck::Yes);
1093
    completionHandler(ShouldContinuePolicyCheck::Yes);
1094
}
1094
}
1095
1095
1096
void CachedResourceStreamingClient::dataReceived(PlatformMediaResource&, Ref<SharedBuffer>&& buffer)
1096
void CachedResourceStreamingClient::dataReceived(PlatformMediaResource&, Ref<FragmentedSharedBuffer>&& buffer)
1097
{
1097
{
1098
    ASSERT(isMainThread());
1098
    ASSERT(isMainThread());
1099
    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
1099
    WebKitWebSrc* src = WEBKIT_WEB_SRC(m_src.get());
- a/Source/WebCore/platform/graphics/gstreamer/eme/CDMProxyClearKey.h -3 / +3 lines
Lines 62-72 public: a/Source/WebCore/platform/graphics/gstreamer/eme/CDMProxyClearKey.h_sec1
62
    CDMProxyClearKey() = default;
62
    CDMProxyClearKey() = default;
63
    virtual ~CDMProxyClearKey();
63
    virtual ~CDMProxyClearKey();
64
64
65
    // FIXME: There's a lack of consistency between SharedBuffers,
65
    // FIXME: There's a lack of consistency between FragmentedSharedBuffers,
66
    // Vector<char>'s and {uint8_t*,size_t} idioms for representing a chunk of
66
    // Vector<char>'s and {uint8_t*,size_t} idioms for representing a chunk of
67
    // bytes. Fix that somehow. Note SharedBuffers are dangerous since
67
    // bytes. Fix that somehow. Note FragmentedSharedBuffers are dangerous since
68
    // they're not thread-safe and this class must maintain
68
    // they're not thread-safe and this class must maintain
69
    // thread-safety, but maybe SharedBuffer::DataSegment could be
69
    // thread-safety, but maybe FragmentedSharedBuffer::DataSegment could be
70
    // made to work, however that has zero helpers for dropping into
70
    // made to work, however that has zero helpers for dropping into
71
    // iterator-aware / comparator-aware containers...
71
    // iterator-aware / comparator-aware containers...
72
    struct cencDecryptContext {
72
    struct cencDecryptContext {
- a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp -19 / +19 lines
Lines 220-226 bool CDMPrivateThunder::supportsSessions() const a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec1
220
    return true;
220
    return true;
221
}
221
}
222
222
223
bool CDMPrivateThunder::supportsInitData(const AtomString& initDataType, const SharedBuffer& initData) const
223
bool CDMPrivateThunder::supportsInitData(const AtomString& initDataType, const FragmentedSharedBuffer& initData) const
224
{
224
{
225
    // Validate the initData buffer as an JSON object in keyids case.
225
    // Validate the initData buffer as an JSON object in keyids case.
226
    if (equalLettersIgnoringASCIICase(initDataType, "keyids") && CDMUtilities::parseJSONObject(initData))
226
    if (equalLettersIgnoringASCIICase(initDataType, "keyids") && CDMUtilities::parseJSONObject(initData))
Lines 237-243 bool CDMPrivateThunder::supportsInitData(const AtomString& initDataType, const S a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec2
237
    return false;
237
    return false;
238
}
238
}
239
239
240
RefPtr<SharedBuffer> CDMPrivateThunder::sanitizeResponse(const SharedBuffer& response) const
240
RefPtr<FragmentedSharedBuffer> CDMPrivateThunder::sanitizeResponse(const FragmentedSharedBuffer& response) const
241
{
241
{
242
    return response.copy();
242
    return response.copy();
243
}
243
}
Lines 260-266 void CDMInstanceThunder::initializeWithConfiguration(const CDMKeySystemConfigura a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec3
260
    callback(Succeeded);
260
    callback(Succeeded);
261
}
261
}
262
262
263
void CDMInstanceThunder::setServerCertificate(Ref<SharedBuffer>&& certificate,  SuccessCallback&& callback)
263
void CDMInstanceThunder::setServerCertificate(Ref<FragmentedSharedBuffer>&& certificate,  SuccessCallback&& callback)
264
{
264
{
265
    OpenCDMError error = opencdm_system_set_server_certificate(m_thunderSystem.get(), const_cast<uint8_t*>(certificate->data()),
265
    OpenCDMError error = opencdm_system_set_server_certificate(m_thunderSystem.get(), const_cast<uint8_t*>(certificate->data()),
266
        certificate->size());
266
        certificate->size());
Lines 326-332 RefPtr<CDMInstanceSession> CDMInstanceThunder::createSession() a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec4
326
class ParsedResponseMessage {
326
class ParsedResponseMessage {
327
327
328
public:
328
public:
329
    ParsedResponseMessage(const RefPtr<SharedBuffer>& buffer)
329
    ParsedResponseMessage(const RefPtr<FragmentedSharedBuffer>& buffer)
330
    {
330
    {
331
        if (!buffer || !buffer->size())
331
        if (!buffer || !buffer->size())
332
            return;
332
            return;
Lines 354-361 public: a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec5
354
354
355
    bool isValid() const { return m_isValid; }
355
    bool isValid() const { return m_isValid; }
356
    bool hasPayload() const { return static_cast<bool>(m_payload); }
356
    bool hasPayload() const { return static_cast<bool>(m_payload); }
357
    const Ref<SharedBuffer>& payload() const& { ASSERT(m_payload); return m_payload.value(); }
357
    const Ref<FragmentedSharedBuffer>& payload() const& { ASSERT(m_payload); return m_payload.value(); }
358
    Ref<SharedBuffer>& payload() & { ASSERT(m_payload); return m_payload.value(); }
358
    Ref<FragmentedSharedBuffer>& payload() & { ASSERT(m_payload); return m_payload.value(); }
359
    bool hasType() const { return m_type.has_value(); }
359
    bool hasType() const { return m_type.has_value(); }
360
    WebCore::MediaKeyMessageType type() const { ASSERT(m_type); return m_type.value(); }
360
    WebCore::MediaKeyMessageType type() const { ASSERT(m_type); return m_type.value(); }
361
    WebCore::MediaKeyMessageType typeOr(WebCore::MediaKeyMessageType alternate) const { return m_type ? m_type.value() : alternate; }
361
    WebCore::MediaKeyMessageType typeOr(WebCore::MediaKeyMessageType alternate) const { return m_type ? m_type.value() : alternate; }
Lines 364-374 public: a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec6
364
364
365
private:
365
private:
366
    bool m_isValid { false };
366
    bool m_isValid { false };
367
    std::optional<Ref<SharedBuffer>> m_payload;
367
    std::optional<Ref<FragmentedSharedBuffer>> m_payload;
368
    std::optional<WebCore::MediaKeyMessageType> m_type;
368
    std::optional<WebCore::MediaKeyMessageType> m_type;
369
};
369
};
370
370
371
void CDMInstanceSessionThunder::challengeGeneratedCallback(RefPtr<SharedBuffer>&& buffer)
371
void CDMInstanceSessionThunder::challengeGeneratedCallback(RefPtr<FragmentedSharedBuffer>&& buffer)
372
{
372
{
373
    ParsedResponseMessage parsedResponseMessage(buffer);
373
    ParsedResponseMessage parsedResponseMessage(buffer);
374
    if (!parsedResponseMessage) {
374
    if (!parsedResponseMessage) {
Lines 475-481 void CDMInstanceSessionThunder::keysUpdateDoneCallback() a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec7
475
    m_sessionChangedCallbacks.clear();
475
    m_sessionChangedCallbacks.clear();
476
}
476
}
477
477
478
void CDMInstanceSessionThunder::errorCallback(RefPtr<SharedBuffer>&& message)
478
void CDMInstanceSessionThunder::errorCallback(RefPtr<FragmentedSharedBuffer>&& message)
479
{
479
{
480
    GST_ERROR("CDM error");
480
    GST_ERROR("CDM error");
481
    GST_MEMDUMP("error dump", message->data(), message->size());
481
    GST_MEMDUMP("error dump", message->data(), message->size());
Lines 488-494 void CDMInstanceSessionThunder::errorCallback(RefPtr<SharedBuffer>&& message) a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec8
488
    m_sessionChangedCallbacks.clear();
488
    m_sessionChangedCallbacks.clear();
489
}
489
}
490
490
491
void CDMInstanceSessionThunder::requestLicense(LicenseType licenseType, const AtomString& initDataType, Ref<SharedBuffer>&& initDataSharedBuffer,
491
void CDMInstanceSessionThunder::requestLicense(LicenseType licenseType, const AtomString& initDataType, Ref<FragmentedSharedBuffer>&& initDataSharedBuffer,
492
    LicenseCallback&& callback)
492
    LicenseCallback&& callback)
493
{
493
{
494
    ASSERT(isMainThread());
494
    ASSERT(isMainThread());
Lines 506-512 void CDMInstanceSessionThunder::requestLicense(LicenseType licenseType, const At a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec9
506
        m_initData.payload()->data(), m_initData.payload()->size(), nullptr, 0, &m_thunderSessionCallbacks, this, &session);
506
        m_initData.payload()->data(), m_initData.payload()->size(), nullptr, 0, &m_thunderSessionCallbacks, this, &session);
507
    if (!session) {
507
    if (!session) {
508
        GST_ERROR("Could not create session");
508
        GST_ERROR("Could not create session");
509
        RefPtr<SharedBuffer> initData = m_initData.payload();
509
        RefPtr<FragmentedSharedBuffer> initData = m_initData.payload();
510
        callback(initData.releaseNonNull(), { }, false, Failed);
510
        callback(initData.releaseNonNull(), { }, false, Failed);
511
        return;
511
        return;
512
    }
512
    }
Lines 515-521 void CDMInstanceSessionThunder::requestLicense(LicenseType licenseType, const At a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec10
515
515
516
    auto generateChallenge = [this, callback = WTFMove(callback)]() mutable {
516
    auto generateChallenge = [this, callback = WTFMove(callback)]() mutable {
517
        ASSERT(isMainThread());
517
        ASSERT(isMainThread());
518
        RefPtr<SharedBuffer> initData = m_initData.payload();
518
        RefPtr<FragmentedSharedBuffer> initData = m_initData.payload();
519
        if (m_sessionID.isEmpty()) {
519
        if (m_sessionID.isEmpty()) {
520
            GST_ERROR("could not create session id");
520
            GST_ERROR("could not create session id");
521
            callback(initData.releaseNonNull(), { }, false, Failed);
521
            callback(initData.releaseNonNull(), { }, false, Failed);
Lines 545-557 void CDMInstanceSessionThunder::sessionFailure() a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec11
545
    m_sessionChangedCallbacks.clear();
545
    m_sessionChangedCallbacks.clear();
546
}
546
}
547
547
548
void CDMInstanceSessionThunder::updateLicense(const String& sessionID, LicenseType, Ref<SharedBuffer>&& response, LicenseUpdateCallback&& callback)
548
void CDMInstanceSessionThunder::updateLicense(const String& sessionID, LicenseType, Ref<FragmentedSharedBuffer>&& response, LicenseUpdateCallback&& callback)
549
{
549
{
550
    ASSERT_UNUSED(sessionID, sessionID == m_sessionID);
550
    ASSERT_UNUSED(sessionID, sessionID == m_sessionID);
551
551
552
    GST_TRACE("Updating session %s", sessionID.utf8().data());
552
    GST_TRACE("Updating session %s", sessionID.utf8().data());
553
553
554
    m_sessionChangedCallbacks.append([this, callback = WTFMove(callback)](bool success, RefPtr<SharedBuffer>&& responseMessage) mutable {
554
    m_sessionChangedCallbacks.append([this, callback = WTFMove(callback)](bool success, RefPtr<FragmentedSharedBuffer>&& responseMessage) mutable {
555
        ASSERT(isMainThread());
555
        ASSERT(isMainThread());
556
        if (success) {
556
        if (success) {
557
            if (!responseMessage)
557
            if (!responseMessage)
Lines 562-568 void CDMInstanceSessionThunder::updateLicense(const String& sessionID, LicenseTy a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec12
562
                ParsedResponseMessage parsedResponseMessage(responseMessage);
562
                ParsedResponseMessage parsedResponseMessage(responseMessage);
563
                ASSERT(parsedResponseMessage);
563
                ASSERT(parsedResponseMessage);
564
                if (parsedResponseMessage.hasPayload()) {
564
                if (parsedResponseMessage.hasPayload()) {
565
                    Ref<SharedBuffer> message = WTFMove(parsedResponseMessage.payload());
565
                    Ref<FragmentedSharedBuffer> message = WTFMove(parsedResponseMessage.payload());
566
                    GST_DEBUG("got message of size %zu", message->size());
566
                    GST_DEBUG("got message of size %zu", message->size());
567
                    GST_MEMDUMP("message", message->data(), message->size());
567
                    GST_MEMDUMP("message", message->data(), message->size());
568
                    callback(false, std::nullopt, std::nullopt,
568
                    callback(false, std::nullopt, std::nullopt,
Lines 586-592 void CDMInstanceSessionThunder::loadSession(LicenseType, const String& sessionID a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec13
586
{
586
{
587
    ASSERT_UNUSED(sessionID, sessionID == m_sessionID);
587
    ASSERT_UNUSED(sessionID, sessionID == m_sessionID);
588
588
589
    m_sessionChangedCallbacks.append([this, callback = WTFMove(callback)](bool success, RefPtr<SharedBuffer>&& responseMessage) mutable {
589
    m_sessionChangedCallbacks.append([this, callback = WTFMove(callback)](bool success, RefPtr<FragmentedSharedBuffer>&& responseMessage) mutable {
590
        ASSERT(isMainThread());
590
        ASSERT(isMainThread());
591
        if (success) {
591
        if (success) {
592
            if (!responseMessage)
592
            if (!responseMessage)
Lines 597-603 void CDMInstanceSessionThunder::loadSession(LicenseType, const String& sessionID a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec14
597
                ParsedResponseMessage parsedResponseMessage(responseMessage);
597
                ParsedResponseMessage parsedResponseMessage(responseMessage);
598
                ASSERT(parsedResponseMessage);
598
                ASSERT(parsedResponseMessage);
599
                if (parsedResponseMessage.hasPayload()) {
599
                if (parsedResponseMessage.hasPayload()) {
600
                    Ref<SharedBuffer> message = WTFMove(parsedResponseMessage.payload());
600
                    Ref<FragmentedSharedBuffer> message = WTFMove(parsedResponseMessage.payload());
601
                    GST_DEBUG("got message of size %zu", message->size());
601
                    GST_DEBUG("got message of size %zu", message->size());
602
                    GST_MEMDUMP("message", message->data(), message->size());
602
                    GST_MEMDUMP("message", message->data(), message->size());
603
                    callback(std::nullopt, std::nullopt, std::make_pair(parsedResponseMessage.typeOr(MediaKeyMessageType::LicenseRequest),
603
                    callback(std::nullopt, std::nullopt, std::make_pair(parsedResponseMessage.typeOr(MediaKeyMessageType::LicenseRequest),
Lines 640-646 void CDMInstanceSessionThunder::removeSessionData(const String& sessionID, Licen a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec15
640
{
640
{
641
    ASSERT_UNUSED(sessionID, m_sessionID == sessionID);
641
    ASSERT_UNUSED(sessionID, m_sessionID == sessionID);
642
642
643
    m_sessionChangedCallbacks.append([this, callback = WTFMove(callback)](bool success, RefPtr<SharedBuffer>&& buffer) mutable {
643
    m_sessionChangedCallbacks.append([this, callback = WTFMove(callback)](bool success, RefPtr<FragmentedSharedBuffer>&& buffer) mutable {
644
        ASSERT(isMainThread());
644
        ASSERT(isMainThread());
645
        if (success) {
645
        if (success) {
646
            if (!buffer)
646
            if (!buffer)
Lines 649-655 void CDMInstanceSessionThunder::removeSessionData(const String& sessionID, Licen a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.cpp_sec16
649
                ParsedResponseMessage parsedResponseMessage(buffer);
649
                ParsedResponseMessage parsedResponseMessage(buffer);
650
                ASSERT(parsedResponseMessage);
650
                ASSERT(parsedResponseMessage);
651
                if (parsedResponseMessage.hasPayload()) {
651
                if (parsedResponseMessage.hasPayload()) {
652
                    Ref<SharedBuffer> message = WTFMove(parsedResponseMessage.payload());
652
                    Ref<FragmentedSharedBuffer> message = WTFMove(parsedResponseMessage.payload());
653
                    GST_DEBUG("session %s removed, message length %zu", m_sessionID.utf8().data(), message->size());
653
                    GST_DEBUG("session %s removed, message length %zu", m_sessionID.utf8().data(), message->size());
654
                    callback(m_keyStore.allKeysAs(MediaKeyStatus::Released), WTFMove(message), SuccessValue::Succeeded);
654
                    callback(m_keyStore.allKeysAs(MediaKeyStatus::Released), WTFMove(message), SuccessValue::Succeeded);
655
                } else {
655
                } else {
- a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.h -10 / +10 lines
Lines 93-100 public: a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.h_sec1
93
    void loadAndInitialize() final;
93
    void loadAndInitialize() final;
94
    bool supportsServerCertificates() const final;
94
    bool supportsServerCertificates() const final;
95
    bool supportsSessions() const final;
95
    bool supportsSessions() const final;
96
    bool supportsInitData(const AtomString&, const SharedBuffer&) const final;
96
    bool supportsInitData(const AtomString&, const FragmentedSharedBuffer&) const final;
97
    RefPtr<SharedBuffer> sanitizeResponse(const SharedBuffer&) const final;
97
    RefPtr<FragmentedSharedBuffer> sanitizeResponse(const FragmentedSharedBuffer&) const final;
98
    std::optional<String> sanitizeSessionId(const String&) const final;
98
    std::optional<String> sanitizeSessionId(const String&) const final;
99
99
100
private:
100
private:
Lines 110-116 public: a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.h_sec2
110
    // CDMInstance
110
    // CDMInstance
111
    ImplementationType implementationType() const final { return ImplementationType::Thunder; }
111
    ImplementationType implementationType() const final { return ImplementationType::Thunder; }
112
    void initializeWithConfiguration(const CDMKeySystemConfiguration&, AllowDistinctiveIdentifiers, AllowPersistentState, SuccessCallback&&) final;
112
    void initializeWithConfiguration(const CDMKeySystemConfiguration&, AllowDistinctiveIdentifiers, AllowPersistentState, SuccessCallback&&) final;
113
    void setServerCertificate(Ref<SharedBuffer>&&, SuccessCallback&&) final;
113
    void setServerCertificate(Ref<FragmentedSharedBuffer>&&, SuccessCallback&&) final;
114
    void setStorageDirectory(const String&) final;
114
    void setStorageDirectory(const String&) final;
115
    const String& keySystem() const final { return m_keySystem; }
115
    const String& keySystem() const final { return m_keySystem; }
116
    RefPtr<CDMInstanceSession> createSession() final;
116
    RefPtr<CDMInstanceSession> createSession() final;
Lines 126-133 class CDMInstanceSessionThunder final : public CDMInstanceSessionProxy { a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.h_sec3
126
public:
126
public:
127
    CDMInstanceSessionThunder(CDMInstanceThunder&);
127
    CDMInstanceSessionThunder(CDMInstanceThunder&);
128
128
129
    void requestLicense(LicenseType, const AtomString& initDataType, Ref<SharedBuffer>&& initData, LicenseCallback&&) final;
129
    void requestLicense(LicenseType, const AtomString& initDataType, Ref<FragmentedSharedBuffer>&& initData, LicenseCallback&&) final;
130
    void updateLicense(const String&, LicenseType, Ref<SharedBuffer>&&, LicenseUpdateCallback&&) final;
130
    void updateLicense(const String&, LicenseType, Ref<FragmentedSharedBuffer>&&, LicenseUpdateCallback&&) final;
131
    void loadSession(LicenseType, const String&, const String&, LoadSessionCallback&&) final;
131
    void loadSession(LicenseType, const String&, const String&, LoadSessionCallback&&) final;
132
    void closeSession(const String&, CloseSessionCallback&&) final;
132
    void closeSession(const String&, CloseSessionCallback&&) final;
133
    void removeSessionData(const String&, LicenseType, RemoveSessionDataCallback&&) final;
133
    void removeSessionData(const String&, LicenseType, RemoveSessionDataCallback&&) final;
Lines 141-154 public: a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.h_sec4
141
private:
141
private:
142
    CDMInstanceThunder* cdmInstanceThunder() const;
142
    CDMInstanceThunder* cdmInstanceThunder() const;
143
143
144
    using Notification = void (CDMInstanceSessionThunder::*)(RefPtr<WebCore::SharedBuffer>&&);
144
    using Notification = void (CDMInstanceSessionThunder::*)(RefPtr<WebCore::FragmentedSharedBuffer>&&);
145
    using ChallengeGeneratedCallback = Function<void()>;
145
    using ChallengeGeneratedCallback = Function<void()>;
146
    using SessionChangedCallback = Function<void(bool, RefPtr<SharedBuffer>&&)>;
146
    using SessionChangedCallback = Function<void(bool, RefPtr<FragmentedSharedBuffer>&&)>;
147
147
148
    void challengeGeneratedCallback(RefPtr<SharedBuffer>&&);
148
    void challengeGeneratedCallback(RefPtr<FragmentedSharedBuffer>&&);
149
    void keyUpdatedCallback(KeyIDType&&);
149
    void keyUpdatedCallback(KeyIDType&&);
150
    void keysUpdateDoneCallback();
150
    void keysUpdateDoneCallback();
151
    void errorCallback(RefPtr<SharedBuffer>&&);
151
    void errorCallback(RefPtr<FragmentedSharedBuffer>&&);
152
    CDMInstanceSession::KeyStatus status(const KeyIDType&) const;
152
    CDMInstanceSession::KeyStatus status(const KeyIDType&) const;
153
    void sessionFailure();
153
    void sessionFailure();
154
154
Lines 159-165 private: a/Source/WebCore/platform/graphics/gstreamer/eme/CDMThunder.h_sec5
159
    InitData m_initData;
159
    InitData m_initData;
160
    OpenCDMSessionCallbacks m_thunderSessionCallbacks { };
160
    OpenCDMSessionCallbacks m_thunderSessionCallbacks { };
161
    BoxPtr<OpenCDMSession> m_session;
161
    BoxPtr<OpenCDMSession> m_session;
162
    RefPtr<SharedBuffer> m_message;
162
    RefPtr<FragmentedSharedBuffer> m_message;
163
    bool m_needsIndividualization { false };
163
    bool m_needsIndividualization { false };
164
    Vector<ChallengeGeneratedCallback> m_challengeCallbacks;
164
    Vector<ChallengeGeneratedCallback> m_challengeCallbacks;
165
    Vector<SessionChangedCallback> m_sessionChangedCallbacks;
165
    Vector<SessionChangedCallback> m_sessionChangedCallbacks;
- a/Source/WebCore/platform/graphics/gstreamer/eme/GStreamerEMEUtilities.cpp -1 / +1 lines
Lines 71-77 static void markupError(GMarkupParseContext*, GError*, gpointer) a/Source/WebCore/platform/graphics/gstreamer/eme/GStreamerEMEUtilities.cpp_sec1
71
71
72
static GMarkupParser markupParser { markupStartElement, markupEndElement, markupText, markupPassthrough, markupError };
72
static GMarkupParser markupParser { markupStartElement, markupEndElement, markupText, markupPassthrough, markupError };
73
73
74
RefPtr<SharedBuffer> InitData::extractCencIfNeeded(RefPtr<SharedBuffer>&& unparsedPayload)
74
RefPtr<FragmentedSharedBuffer> InitData::extractCencIfNeeded(RefPtr<SharedBuffer>&& unparsedPayload)
75
{
75
{
76
    RefPtr<SharedBuffer> payload = WTFMove(unparsedPayload);
76
    RefPtr<SharedBuffer> payload = WTFMove(unparsedPayload);
77
    if (!payload || !payload->size())
77
    if (!payload || !payload->size())
- a/Source/WebCore/platform/graphics/gstreamer/eme/GStreamerEMEUtilities.h -9 / +12 lines
Lines 38-45 GST_DEBUG_CATEGORY_EXTERN(webkit_media_common_encryption_decrypt_debug_category) a/Source/WebCore/platform/graphics/gstreamer/eme/GStreamerEMEUtilities.h_sec1
38
namespace WebCore {
38
namespace WebCore {
39
class InitData {
39
class InitData {
40
public:
40
public:
41
    InitData()
41
    InitData() = default;
42
        : m_payload(SharedBuffer::create()) { }
43
42
44
    // FIXME: We should have an enum for system uuids for better type safety.
43
    // FIXME: We should have an enum for system uuids for better type safety.
45
    InitData(const String& systemId, GstBuffer* initData)
44
    InitData(const String& systemId, GstBuffer* initData)
Lines 50-62 public: a/Source/WebCore/platform/graphics/gstreamer/eme/GStreamerEMEUtilities.h_sec2
50
            GST_CAT_LEVEL_LOG(webkit_media_common_encryption_decrypt_debug_category, GST_LEVEL_ERROR, nullptr, "cannot map %s protection data", systemId.utf8().data());
49
            GST_CAT_LEVEL_LOG(webkit_media_common_encryption_decrypt_debug_category, GST_LEVEL_ERROR, nullptr, "cannot map %s protection data", systemId.utf8().data());
51
            ASSERT_NOT_REACHED();
50
            ASSERT_NOT_REACHED();
52
        }
51
        }
53
        m_payload = extractCencIfNeeded(mappedInitData->createSharedBuffer());
52
        if (auto parsedPayload = extractCencIfNeeded(mappedInitData->createSharedBuffer()))
53
            m_payload.append(parsedPayload.releaseNonNull());
54
    }
54
    }
55
55
56
    InitData(const String& systemId, RefPtr<SharedBuffer>&& payload)
56
    InitData(const String& systemId, RefPtr<FragmentedSharedBuffer>&& payload)
57
        : m_systemId(systemId)
57
        : m_systemId(systemId)
58
        , m_payload(extractCencIfNeeded(WTFMove(payload)))
59
    {
58
    {
59
        if (payload) {
60
            if (auto parsedPayload = extractCencIfNeeded(payload->makeContiguous()))
61
                m_payload.append(parsedPayload.releaseNonNull());
62
        }
60
    }
63
    }
61
64
62
    void append(InitData&& initData)
65
    void append(InitData&& initData)
Lines 72-81 public: a/Source/WebCore/platform/graphics/gstreamer/eme/GStreamerEMEUtilities.h_sec3
72
        // it's not very robust, so be careful here!
75
        // it's not very robust, so be careful here!
73
        m_systemId = initData.m_systemId;
76
        m_systemId = initData.m_systemId;
74
77
75
        m_payload->append(*initData.payload());
78
        m_payload.append(*initData.payload());
76
    }
79
    }
77
80
78
    const RefPtr<SharedBuffer>& payload() const { return m_payload; }
81
    RefPtr<FragmentedSharedBuffer> payload() const { return m_payload.get(); }
79
    const String& systemId() const { return m_systemId; }
82
    const String& systemId() const { return m_systemId; }
80
    String payloadContainerType() const
83
    String payloadContainerType() const
81
    {
84
    {
Lines 86-96 public: a/Source/WebCore/platform/graphics/gstreamer/eme/GStreamerEMEUtilities.h_sec4
86
        return "cenc"_s;
89
        return "cenc"_s;
87
    }
90
    }
88
91
89
    static RefPtr<SharedBuffer> extractCencIfNeeded(RefPtr<SharedBuffer>&&);
92
    static RefPtr<FragmentedSharedBuffer> extractCencIfNeeded(RefPtr<SharedBuffer>&&);
90
93
91
private:
94
private:
92
    String m_systemId;
95
    String m_systemId;
93
    RefPtr<SharedBuffer> m_payload;
96
    SharedBufferBuilder m_payload;
94
};
97
};
95
98
96
class ProtectionSystemEvents {
99
class ProtectionSystemEvents {
- a/Source/WebCore/platform/graphics/mac/FontCustomPlatformData.h -1 / +1 lines
Lines 36-42 namespace WebCore { a/Source/WebCore/platform/graphics/mac/FontCustomPlatformData.h_sec1
36
class FontCreationContext;
36
class FontCreationContext;
37
class FontDescription;
37
class FontDescription;
38
struct FontSelectionSpecifiedCapabilities;
38
struct FontSelectionSpecifiedCapabilities;
39
class SharedBuffer;
39
class FragmentedSharedBuffer;
40
40
41
template <typename T> class FontTaggedSettings;
41
template <typename T> class FontTaggedSettings;
42
typedef FontTaggedSettings<int> FontFeatureSettings;
42
typedef FontTaggedSettings<int> FontFeatureSettings;
- a/Source/WebCore/platform/graphics/mac/PDFDocumentImageMac.mm -1 / +1 lines
Lines 48-54 namespace WebCore { a/Source/WebCore/platform/graphics/mac/PDFDocumentImageMac.mm_sec1
48
48
49
void PDFDocumentImage::createPDFDocument()
49
void PDFDocumentImage::createPDFDocument()
50
{
50
{
51
    m_document = adoptNS([allocPDFDocumentInstance() initWithData:data()->createNSData().get()]);
51
    m_document = adoptNS([allocPDFDocumentInstance() initWithData:data()->makeContiguous()->createNSData().get()]);
52
}
52
}
53
53
54
void PDFDocumentImage::computeBoundsForCurrentPage()
54
void PDFDocumentImage::computeBoundsForCurrentPage()
- a/Source/WebCore/platform/graphics/opentype/OpenTypeUtilities.h -1 / +2 lines
Lines 35-43 a/Source/WebCore/platform/graphics/opentype/OpenTypeUtilities.h_sec1
35
namespace WebCore {
35
namespace WebCore {
36
36
37
struct BigEndianUShort;
37
struct BigEndianUShort;
38
class SharedBuffer;
38
struct EOTPrefix;
39
struct EOTPrefix;
39
class FontMemoryResource;
40
class FontMemoryResource;
40
class SharedBuffer;
41
class FragmentedSharedBuffer;
41
42
42
struct EOTHeader {
43
struct EOTHeader {
43
    EOTHeader();
44
    EOTHeader();
- a/Source/WebCore/platform/graphics/opentype/OpenTypeVerticalData.cpp -3 / +3 lines
Lines 381-387 struct GSUBTable : TableBase { a/Source/WebCore/platform/graphics/opentype/OpenTypeVerticalData.cpp_sec1
381
381
382
static bool loadHmtxTable(const FontPlatformData& platformData, Vector<uint16_t>& advanceWidths)
382
static bool loadHmtxTable(const FontPlatformData& platformData, Vector<uint16_t>& advanceWidths)
383
{
383
{
384
    RefPtr<SharedBuffer> buffer = platformData.openTypeTable(OpenType::HheaTag);
384
    auto buffer = platformData.openTypeTable(OpenType::HheaTag);
385
    const OpenType::HheaTable* hhea = OpenType::validateTable<OpenType::HheaTable>(buffer);
385
    const OpenType::HheaTable* hhea = OpenType::validateTable<OpenType::HheaTable>(buffer);
386
    if (!hhea)
386
    if (!hhea)
387
        return false;
387
        return false;
Lines 424-430 OpenTypeVerticalData::OpenTypeVerticalData(const FontPlatformData& platformData, a/Source/WebCore/platform/graphics/opentype/OpenTypeVerticalData.cpp_sec2
424
void OpenTypeVerticalData::loadMetrics(const FontPlatformData& platformData)
424
void OpenTypeVerticalData::loadMetrics(const FontPlatformData& platformData)
425
{
425
{
426
    // Load vhea first. This table is required for fonts that support vertical flow.
426
    // Load vhea first. This table is required for fonts that support vertical flow.
427
    RefPtr<SharedBuffer> buffer = platformData.openTypeTable(OpenType::VheaTag);
427
    auto buffer = platformData.openTypeTable(OpenType::VheaTag);
428
    const OpenType::VheaTable* vhea = OpenType::validateTable<OpenType::VheaTable>(buffer);
428
    const OpenType::VheaTable* vhea = OpenType::validateTable<OpenType::VheaTable>(buffer);
429
    if (!vhea)
429
    if (!vhea)
430
        return;
430
        return;
Lines 486-492 void OpenTypeVerticalData::loadMetrics(const FontPlatformData& platformData) a/Source/WebCore/platform/graphics/opentype/OpenTypeVerticalData.cpp_sec3
486
486
487
void OpenTypeVerticalData::loadVerticalGlyphSubstitutions(const FontPlatformData& platformData)
487
void OpenTypeVerticalData::loadVerticalGlyphSubstitutions(const FontPlatformData& platformData)
488
{
488
{
489
    RefPtr<SharedBuffer> buffer = platformData.openTypeTable(OpenType::GSUBTag);
489
    auto buffer = platformData.openTypeTable(OpenType::GSUBTag);
490
    const OpenType::GSUBTable* gsub = OpenType::validateTable<OpenType::GSUBTable>(buffer);
490
    const OpenType::GSUBTable* gsub = OpenType::validateTable<OpenType::GSUBTable>(buffer);
491
    if (gsub)
491
    if (gsub)
492
        gsub->getVerticalGlyphSubstitutions(&m_verticalGlyphMap, *buffer.get());
492
        gsub->getVerticalGlyphSubstitutions(&m_verticalGlyphMap, *buffer.get());
- a/Source/WebCore/platform/graphics/win/DirectWriteUtilities.h -1 / +1 lines
Lines 43-49 enum DWRITE_FONT_STRETCH; a/Source/WebCore/platform/graphics/win/DirectWriteUtilities.h_sec1
43
namespace WebCore {
43
namespace WebCore {
44
44
45
class FontPlatformData;
45
class FontPlatformData;
46
class SharedBuffer;
46
class FragmentedSharedBuffer;
47
47
48
namespace DirectWrite {
48
namespace DirectWrite {
49
49
- a/Source/WebCore/platform/graphics/win/FontCustomPlatformData.h -1 / +2 lines
Lines 36-47 typedef struct CGFont* CGFontRef; a/Source/WebCore/platform/graphics/win/FontCustomPlatformData.h_sec1
36
36
37
namespace WebCore {
37
namespace WebCore {
38
38
39
class SharedBuffer;
39
class FontCreationContext;
40
class FontCreationContext;
40
class FontDescription;
41
class FontDescription;
41
class FontMemoryResource;
42
class FontMemoryResource;
42
class SharedBuffer;
43
struct FontSelectionSpecifiedCapabilities;
43
struct FontSelectionSpecifiedCapabilities;
44
struct FontVariantSettings;
44
struct FontVariantSettings;
45
class FragmentedSharedBuffer;
45
46
46
template <typename T> class FontTaggedSettings;
47
template <typename T> class FontTaggedSettings;
47
typedef FontTaggedSettings<int> FontFeatureSettings;
48
typedef FontTaggedSettings<int> FontFeatureSettings;
- a/Source/WebCore/platform/graphics/win/ImageDecoderDirect2D.cpp -1 / +1 lines
Lines 272-278 PlatformImagePtr ImageDecoderDirect2D::createFrameImageAtIndex(size_t index, Sub a/Source/WebCore/platform/graphics/win/ImageDecoderDirect2D.cpp_sec1
272
    return bitmap;
272
    return bitmap;
273
}
273
}
274
274
275
void ImageDecoderDirect2D::setData(SharedBuffer& data, bool allDataReceived)
275
void ImageDecoderDirect2D::setData(FragmentedSharedBuffer& data, bool allDataReceived)
276
{
276
{
277
    if (!allDataReceived)
277
    if (!allDataReceived)
278
        return;
278
        return;
- a/Source/WebCore/platform/graphics/win/ImageDecoderDirect2D.h -2 / +2 lines
Lines 41-47 class ImageDecoderDirect2D final : public ImageDecoder { a/Source/WebCore/platform/graphics/win/ImageDecoderDirect2D.h_sec1
41
public:
41
public:
42
    ImageDecoderDirect2D();
42
    ImageDecoderDirect2D();
43
43
44
    static Ref<ImageDecoderDirect2D> create(SharedBuffer&, AlphaOption, GammaAndColorProfileOption)
44
    static Ref<ImageDecoderDirect2D> create(FragmentedSharedBuffer&, AlphaOption, GammaAndColorProfileOption)
45
    {
45
    {
46
        return adoptRef(*new ImageDecoderDirect2D());
46
        return adoptRef(*new ImageDecoderDirect2D());
47
    }
47
    }
Lines 72-78 public: a/Source/WebCore/platform/graphics/win/ImageDecoderDirect2D.h_sec2
72
72
73
    PlatformImagePtr createFrameImageAtIndex(size_t, SubsamplingLevel = SubsamplingLevel::Default, const DecodingOptions& = DecodingOptions(DecodingMode::Synchronous)) final;
73
    PlatformImagePtr createFrameImageAtIndex(size_t, SubsamplingLevel = SubsamplingLevel::Default, const DecodingOptions& = DecodingOptions(DecodingMode::Synchronous)) final;
74
74
75
    void setData(SharedBuffer&, bool allDataReceived) final;
75
    void setData(FragmentedSharedBuffer&, bool allDataReceived) final;
76
    bool isAllDataReceived() const final { return m_isAllDataReceived; }
76
    bool isAllDataReceived() const final { return m_isAllDataReceived; }
77
    void clearFrameBufferCache(size_t) final { }
77
    void clearFrameBufferCache(size_t) final { }
78
78
- a/Source/WebCore/platform/graphics/win/ImageWin.cpp -1 / +1 lines
Lines 30-36 a/Source/WebCore/platform/graphics/win/ImageWin.cpp_sec1
30
#include "SharedBuffer.h"
30
#include "SharedBuffer.h"
31
31
32
// This function loads resources from WebKit
32
// This function loads resources from WebKit
33
RefPtr<WebCore::SharedBuffer> loadResourceIntoBuffer(const char*);
33
RefPtr<WebCore::FragmentedSharedBuffer> loadResourceIntoBuffer(const char*);
34
34
35
namespace WebCore {
35
namespace WebCore {
36
36
- a/Source/WebCore/platform/image-decoders/ScalableImageDecoder.cpp -2 / +2 lines
Lines 51-57 namespace WebCore { a/Source/WebCore/platform/image-decoders/ScalableImageDecoder.cpp_sec1
51
51
52
namespace {
52
namespace {
53
53
54
static unsigned copyFromSharedBuffer(char* buffer, unsigned bufferLength, const SharedBuffer& sharedBuffer)
54
static unsigned copyFromSharedBuffer(char* buffer, unsigned bufferLength, const FragmentedSharedBuffer& sharedBuffer)
55
{
55
{
56
    unsigned bytesExtracted = 0;
56
    unsigned bytesExtracted = 0;
57
    for (const auto& element : sharedBuffer) {
57
    for (const auto& element : sharedBuffer) {
Lines 135-141 bool matchesCURSignature(char* contents) a/Source/WebCore/platform/image-decoders/ScalableImageDecoder.cpp_sec2
135
135
136
}
136
}
137
137
138
RefPtr<ScalableImageDecoder> ScalableImageDecoder::create(SharedBuffer& data, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
138
RefPtr<ScalableImageDecoder> ScalableImageDecoder::create(FragmentedSharedBuffer& data, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
139
{
139
{
140
    static const unsigned lengthOfLongestSignature = 14; // To wit: "RIFF????WEBPVP"
140
    static const unsigned lengthOfLongestSignature = 14; // To wit: "RIFF????WEBPVP"
141
    char contents[lengthOfLongestSignature];
141
    char contents[lengthOfLongestSignature];
- a/Source/WebCore/platform/image-decoders/ScalableImageDecoder.h -7 / +6 lines
Lines 60-66 public: a/Source/WebCore/platform/image-decoders/ScalableImageDecoder.h_sec1
60
60
61
    // Returns nullptr if we can't sniff a supported type from the provided data (possibly
61
    // Returns nullptr if we can't sniff a supported type from the provided data (possibly
62
    // because there isn't enough data yet).
62
    // because there isn't enough data yet).
63
    static RefPtr<ScalableImageDecoder> create(SharedBuffer& data, AlphaOption, GammaAndColorProfileOption);
63
    static RefPtr<ScalableImageDecoder> create(FragmentedSharedBuffer& data, AlphaOption, GammaAndColorProfileOption);
64
64
65
    bool premultiplyAlpha() const { return m_premultiplyAlpha; }
65
    bool premultiplyAlpha() const { return m_premultiplyAlpha; }
66
66
Lines 70-85 public: a/Source/WebCore/platform/image-decoders/ScalableImageDecoder.h_sec2
70
        return m_encodedDataStatus == EncodedDataStatus::Complete;
70
        return m_encodedDataStatus == EncodedDataStatus::Complete;
71
    }
71
    }
72
72
73
    void setData(SharedBuffer& data, bool allDataReceived) override
73
    void setData(FragmentedSharedBuffer& data, bool allDataReceived) override
74
    {
74
    {
75
        Locker locker { m_lock };
75
        Locker locker { m_lock };
76
        if (m_encodedDataStatus == EncodedDataStatus::Error)
76
        if (m_encodedDataStatus == EncodedDataStatus::Error)
77
            return;
77
            return;
78
78
79
        if (data.data()) {
79
        auto contiguousData = data.makeContiguous();
80
            // SharedBuffer::data() combines all segments into one in case there's more than one.
80
        if (contiguousData->data())
81
            m_data = data.begin()->segment.copyRef();
81
            m_data = contiguousData->begin()->segment.copyRef();
82
        }
83
        if (m_encodedDataStatus == EncodedDataStatus::TypeAvailable) {
82
        if (m_encodedDataStatus == EncodedDataStatus::TypeAvailable) {
84
            m_decodingSizeFromSetData = true;
83
            m_decodingSizeFromSetData = true;
85
            tryDecodeSize(allDataReceived);
84
            tryDecodeSize(allDataReceived);
Lines 195-201 public: a/Source/WebCore/platform/image-decoders/ScalableImageDecoder.h_sec3
195
    std::optional<IntPoint> hotSpot() const override { return std::nullopt; }
194
    std::optional<IntPoint> hotSpot() const override { return std::nullopt; }
196
195
197
protected:
196
protected:
198
    RefPtr<SharedBuffer::DataSegment> m_data;
197
    RefPtr<FragmentedSharedBuffer::DataSegment> m_data;
199
    Vector<ScalableImageDecoderFrame, 1> m_frameBufferCache WTF_GUARDED_BY_LOCK(m_lock);
198
    Vector<ScalableImageDecoderFrame, 1> m_frameBufferCache WTF_GUARDED_BY_LOCK(m_lock);
200
    mutable Lock m_lock;
199
    mutable Lock m_lock;
201
    bool m_premultiplyAlpha;
200
    bool m_premultiplyAlpha;
- a/Source/WebCore/platform/image-decoders/avif/AVIFImageReader.cpp -2 / +2 lines
Lines 41-47 AVIFImageReader::AVIFImageReader(RefPtr<AVIFImageDecoder>&& decoder) a/Source/WebCore/platform/image-decoders/avif/AVIFImageReader.cpp_sec1
41
41
42
AVIFImageReader::~AVIFImageReader() = default;
42
AVIFImageReader::~AVIFImageReader() = default;
43
43
44
bool AVIFImageReader::parseHeader(const SharedBuffer::DataSegment& data, bool allDataReceived)
44
bool AVIFImageReader::parseHeader(const FragmentedSharedBuffer::DataSegment& data, bool allDataReceived)
45
{
45
{
46
    if (avifDecoderSetIOMemory(m_avifDecoder.get(), data.data(), data.size()) != AVIF_RESULT_OK)
46
    if (avifDecoderSetIOMemory(m_avifDecoder.get(), data.data(), data.size()) != AVIF_RESULT_OK)
47
        return allDataReceived ? m_decoder->setFailed() : false;
47
        return allDataReceived ? m_decoder->setFailed() : false;
Lines 58-64 bool AVIFImageReader::parseHeader(const SharedBuffer::DataSegment& data, bool al a/Source/WebCore/platform/image-decoders/avif/AVIFImageReader.cpp_sec2
58
    return true;
58
    return true;
59
}
59
}
60
60
61
void AVIFImageReader::decodeFrame(size_t frameIndex, ScalableImageDecoderFrame& buffer, const SharedBuffer::DataSegment& data)
61
void AVIFImageReader::decodeFrame(size_t frameIndex, ScalableImageDecoderFrame& buffer, const FragmentedSharedBuffer::DataSegment& data)
62
{
62
{
63
    if (m_decoder->failed())
63
    if (m_decoder->failed())
64
        return;
64
        return;
- a/Source/WebCore/platform/image-decoders/avif/AVIFImageReader.h -2 / +2 lines
Lines 39-46 public: a/Source/WebCore/platform/image-decoders/avif/AVIFImageReader.h_sec1
39
    AVIFImageReader(RefPtr<AVIFImageDecoder>&&);
39
    AVIFImageReader(RefPtr<AVIFImageDecoder>&&);
40
    ~AVIFImageReader();
40
    ~AVIFImageReader();
41
41
42
    bool parseHeader(const SharedBuffer::DataSegment&, bool allDataReceived);
42
    bool parseHeader(const FragmentedSharedBuffer::DataSegment&, bool allDataReceived);
43
    void decodeFrame(size_t index, ScalableImageDecoderFrame&, const SharedBuffer::DataSegment&);
43
    void decodeFrame(size_t index, ScalableImageDecoderFrame&, const FragmentedSharedBuffer::DataSegment&);
44
    size_t imageCount() const;
44
    size_t imageCount() const;
45
    double repetitionCount() const;
45
    double repetitionCount() const;
46
46
- a/Source/WebCore/platform/image-decoders/bmp/BMPImageDecoder.cpp -1 / +1 lines
Lines 46-52 BMPImageDecoder::BMPImageDecoder(AlphaOption alphaOption, GammaAndColorProfileOp a/Source/WebCore/platform/image-decoders/bmp/BMPImageDecoder.cpp_sec1
46
{
46
{
47
}
47
}
48
48
49
void BMPImageDecoder::setData(SharedBuffer& data, bool allDataReceived)
49
void BMPImageDecoder::setData(FragmentedSharedBuffer& data, bool allDataReceived)
50
{
50
{
51
    if (failed())
51
    if (failed())
52
        return;
52
        return;
- a/Source/WebCore/platform/image-decoders/bmp/BMPImageDecoder.h -1 / +1 lines
Lines 44-50 public: a/Source/WebCore/platform/image-decoders/bmp/BMPImageDecoder.h_sec1
44
44
45
    // ScalableImageDecoder
45
    // ScalableImageDecoder
46
    String filenameExtension() const final { return "bmp"_s; }
46
    String filenameExtension() const final { return "bmp"_s; }
47
    void setData(SharedBuffer&, bool allDataReceived) final;
47
    void setData(FragmentedSharedBuffer&, bool allDataReceived) final;
48
    ScalableImageDecoderFrame* frameBufferAtIndex(size_t index) final;
48
    ScalableImageDecoderFrame* frameBufferAtIndex(size_t index) final;
49
    // CAUTION: setFailed() deletes |m_reader|. Be careful to avoid
49
    // CAUTION: setFailed() deletes |m_reader|. Be careful to avoid
50
    // accessing deleted memory, especially when calling this from inside
50
    // accessing deleted memory, especially when calling this from inside
- a/Source/WebCore/platform/image-decoders/bmp/BMPImageReader.h -4 / +4 lines
Lines 42-48 class BMPImageReader { a/Source/WebCore/platform/image-decoders/bmp/BMPImageReader.h_sec1
42
public:
42
public:
43
    // Read a value from |data[offset]|, converting from little to native
43
    // Read a value from |data[offset]|, converting from little to native
44
    // endianness.
44
    // endianness.
45
    static inline uint16_t readUint16(const SharedBuffer::DataSegment& data, int offset)
45
    static inline uint16_t readUint16(const FragmentedSharedBuffer::DataSegment& data, int offset)
46
    {
46
    {
47
        uint16_t result;
47
        uint16_t result;
48
        memcpy(&result, &data.data()[offset], 2);
48
        memcpy(&result, &data.data()[offset], 2);
Lines 52-58 public: a/Source/WebCore/platform/image-decoders/bmp/BMPImageReader.h_sec2
52
        return result;
52
        return result;
53
    }
53
    }
54
54
55
    static inline uint32_t readUint32(const SharedBuffer::DataSegment& data, int offset)
55
    static inline uint32_t readUint32(const FragmentedSharedBuffer::DataSegment& data, int offset)
56
    {
56
    {
57
        uint32_t result;
57
        uint32_t result;
58
        memcpy(&result, &data.data()[offset], 4);
58
        memcpy(&result, &data.data()[offset], 4);
Lines 69-75 public: a/Source/WebCore/platform/image-decoders/bmp/BMPImageReader.h_sec3
69
    BMPImageReader(ScalableImageDecoder* parent, size_t decodedAndHeaderOffset, size_t imgDataOffset, bool usesAndMask);
69
    BMPImageReader(ScalableImageDecoder* parent, size_t decodedAndHeaderOffset, size_t imgDataOffset, bool usesAndMask);
70
70
71
    void setBuffer(ScalableImageDecoderFrame* buffer) { m_buffer = buffer; }
71
    void setBuffer(ScalableImageDecoderFrame* buffer) { m_buffer = buffer; }
72
    void setData(SharedBuffer::DataSegment& data) { m_data = &data; }
72
    void setData(FragmentedSharedBuffer::DataSegment& data) { m_data = &data; }
73
73
74
    // Does the actual decoding. If |onlySize| is true, decoding only
74
    // Does the actual decoding. If |onlySize| is true, decoding only
75
    // progresses as far as necessary to get the image size. Returns
75
    // progresses as far as necessary to get the image size. Returns
Lines 272-278 private: a/Source/WebCore/platform/image-decoders/bmp/BMPImageReader.h_sec4
272
    ScalableImageDecoderFrame* m_buffer;
272
    ScalableImageDecoderFrame* m_buffer;
273
273
274
    // The file to decode.
274
    // The file to decode.
275
    RefPtr<SharedBuffer::DataSegment> m_data;
275
    RefPtr<FragmentedSharedBuffer::DataSegment> m_data;
276
276
277
    // An index into |m_data| representing how much we've already decoded.
277
    // An index into |m_data| representing how much we've already decoded.
278
    size_t m_decodedOffset;
278
    size_t m_decodedOffset;
- a/Source/WebCore/platform/image-decoders/cairo/ImageBackingStoreCairo.cpp -1 / +3 lines
Lines 37-43 PlatformImagePtr ImageBackingStore::image() const a/Source/WebCore/platform/image-decoders/cairo/ImageBackingStoreCairo.cpp_sec1
37
        reinterpret_cast<unsigned char*>(const_cast<uint32_t*>(m_pixelsPtr)),
37
        reinterpret_cast<unsigned char*>(const_cast<uint32_t*>(m_pixelsPtr)),
38
        CAIRO_FORMAT_ARGB32, size().width(), size().height(), size().width() * sizeof(uint32_t)));
38
        CAIRO_FORMAT_ARGB32, size().width(), size().height(), size().width() * sizeof(uint32_t)));
39
    static cairo_user_data_key_t s_surfaceDataKey;
39
    static cairo_user_data_key_t s_surfaceDataKey;
40
    cairo_surface_set_user_data(surface.get(), &s_surfaceDataKey, m_pixels.get(), [](void* data) { static_cast<SharedBuffer::DataSegment*>(data)->deref(); });
40
    cairo_surface_set_user_data(surface.get(), &s_surfaceDataKey, m_pixels.get(), [](void* data) {
41
        static_cast<DataSegment*>(data)->deref();
42
    });
41
43
42
    return surface;
44
    return surface;
43
}
45
}
- a/Source/WebCore/platform/image-decoders/gif/GIFImageDecoder.cpp -1 / +1 lines
Lines 38-44 GIFImageDecoder::GIFImageDecoder(AlphaOption alphaOption, GammaAndColorProfileOp a/Source/WebCore/platform/image-decoders/gif/GIFImageDecoder.cpp_sec1
38
38
39
GIFImageDecoder::~GIFImageDecoder() = default;
39
GIFImageDecoder::~GIFImageDecoder() = default;
40
40
41
void GIFImageDecoder::setData(SharedBuffer& data, bool allDataReceived)
41
void GIFImageDecoder::setData(FragmentedSharedBuffer& data, bool allDataReceived)
42
{
42
{
43
    if (failed())
43
    if (failed())
44
        return;
44
        return;
- a/Source/WebCore/platform/image-decoders/gif/GIFImageDecoder.h -1 / +1 lines
Lines 46-52 public: a/Source/WebCore/platform/image-decoders/gif/GIFImageDecoder.h_sec1
46
46
47
    // ScalableImageDecoder
47
    // ScalableImageDecoder
48
    String filenameExtension() const final { return "gif"_s; }
48
    String filenameExtension() const final { return "gif"_s; }
49
    void setData(SharedBuffer& data, bool allDataReceived) final;
49
    void setData(FragmentedSharedBuffer& data, bool allDataReceived) final;
50
    bool setSize(const IntSize&) final;
50
    bool setSize(const IntSize&) final;
51
    size_t frameCount() const final;
51
    size_t frameCount() const final;
52
    RepetitionCount repetitionCount() const final;
52
    RepetitionCount repetitionCount() const final;
- a/Source/WebCore/platform/image-decoders/gif/GIFImageReader.h -2 / +2 lines
Lines 237-243 public: a/Source/WebCore/platform/image-decoders/gif/GIFImageReader.h_sec1
237
    {
237
    {
238
    }
238
    }
239
239
240
    void setData(WebCore::SharedBuffer::DataSegment& data) { m_data = &data; }
240
    void setData(WebCore::FragmentedSharedBuffer::DataSegment& data) { m_data = &data; }
241
    // FIXME: haltAtFrame should be size_t.
241
    // FIXME: haltAtFrame should be size_t.
242
    bool decode(WebCore::GIFImageDecoder::GIFQuery, unsigned haltAtFrame);
242
    bool decode(WebCore::GIFImageDecoder::GIFQuery, unsigned haltAtFrame);
243
243
Lines 316-321 private: a/Source/WebCore/platform/image-decoders/gif/GIFImageReader.h_sec2
316
    Vector<std::unique_ptr<GIFFrameContext> > m_frames;
316
    Vector<std::unique_ptr<GIFFrameContext> > m_frames;
317
    size_t m_currentDecodingFrame;
317
    size_t m_currentDecodingFrame;
318
318
319
    RefPtr<WebCore::SharedBuffer::DataSegment> m_data;
319
    RefPtr<WebCore::FragmentedSharedBuffer::DataSegment> m_data;
320
    bool m_parseCompleted;
320
    bool m_parseCompleted;
321
};
321
};
- a/Source/WebCore/platform/image-decoders/ico/ICOImageDecoder.cpp -1 / +1 lines
Lines 52-58 ICOImageDecoder::ICOImageDecoder(AlphaOption alphaOption, GammaAndColorProfileOp a/Source/WebCore/platform/image-decoders/ico/ICOImageDecoder.cpp_sec1
52
52
53
ICOImageDecoder::~ICOImageDecoder() = default;
53
ICOImageDecoder::~ICOImageDecoder() = default;
54
54
55
void ICOImageDecoder::setData(SharedBuffer& data, bool allDataReceived)
55
void ICOImageDecoder::setData(FragmentedSharedBuffer& data, bool allDataReceived)
56
{
56
{
57
    if (failed())
57
    if (failed())
58
        return;
58
        return;
- a/Source/WebCore/platform/image-decoders/ico/ICOImageDecoder.h -1 / +1 lines
Lines 46-52 public: a/Source/WebCore/platform/image-decoders/ico/ICOImageDecoder.h_sec1
46
46
47
    // ScalableImageDecoder
47
    // ScalableImageDecoder
48
    String filenameExtension() const final { return "ico"_s; }
48
    String filenameExtension() const final { return "ico"_s; }
49
    void setData(SharedBuffer&, bool allDataReceived) final;
49
    void setData(FragmentedSharedBuffer&, bool allDataReceived) final;
50
    IntSize size() const final;
50
    IntSize size() const final;
51
    IntSize frameSizeAtIndex(size_t, SubsamplingLevel) const final;
51
    IntSize frameSizeAtIndex(size_t, SubsamplingLevel) const final;
52
    bool setSize(const IntSize&) final;
52
    bool setSize(const IntSize&) final;
- a/Source/WebCore/platform/image-decoders/jpeg/JPEGImageDecoder.cpp -5 / +5 lines
Lines 222-228 static bool isICCMarker(jpeg_saved_marker_ptr marker) a/Source/WebCore/platform/image-decoders/jpeg/JPEGImageDecoder.cpp_sec1
222
222
223
static RefPtr<SharedBuffer> readICCProfile(jpeg_decompress_struct* info)
223
static RefPtr<SharedBuffer> readICCProfile(jpeg_decompress_struct* info)
224
{
224
{
225
    auto buffer = SharedBuffer::create();
225
    SharedBufferBuilder buffer;
226
    for (jpeg_saved_marker_ptr marker = info->marker_list; marker; marker = marker->next) {
226
    for (jpeg_saved_marker_ptr marker = info->marker_list; marker; marker = marker->next) {
227
        if (!isICCMarker(marker))
227
        if (!isICCMarker(marker))
228
            continue;
228
            continue;
Lines 236-248 static RefPtr<SharedBuffer> readICCProfile(jpeg_decompress_struct* info) a/Source/WebCore/platform/image-decoders/jpeg/JPEGImageDecoder.cpp_sec2
236
            return nullptr;
236
            return nullptr;
237
237
238
        unsigned markerSize = marker->data_length - iccHeaderSize;
238
        unsigned markerSize = marker->data_length - iccHeaderSize;
239
        buffer->append(reinterpret_cast<const uint8_t*>(marker->data + iccHeaderSize), markerSize);
239
        buffer.append(reinterpret_cast<const uint8_t*>(marker->data + iccHeaderSize), markerSize);
240
    }
240
    }
241
241
242
    if (buffer->isEmpty())
242
    if (buffer.isEmpty())
243
        return nullptr;
243
        return nullptr;
244
244
245
    return buffer;
245
    return buffer.take()->makeContiguous();
246
}
246
}
247
#endif
247
#endif
248
248
Lines 320-326 public: a/Source/WebCore/platform/image-decoders/jpeg/JPEGImageDecoder.cpp_sec3
320
        m_bytesToSkip = std::max(numBytes - bytesToSkip, static_cast<long>(0));
320
        m_bytesToSkip = std::max(numBytes - bytesToSkip, static_cast<long>(0));
321
    }
321
    }
322
322
323
    bool decode(const SharedBuffer::DataSegment& data, bool onlySize)
323
    bool decode(const FragmentedSharedBuffer::DataSegment& data, bool onlySize)
324
    {
324
    {
325
        m_decodingSizeOnly = onlySize;
325
        m_decodingSizeOnly = onlySize;
326
326
- a/Source/WebCore/platform/image-decoders/jpeg2000/JPEG2000ImageDecoder.cpp -1 / +1 lines
Lines 380-386 void JPEG2000ImageDecoder::decode(bool onlySize, bool allDataReceived) a/Source/WebCore/platform/image-decoders/jpeg2000/JPEG2000ImageDecoder.cpp_sec1
380
    }
380
    }
381
381
382
    struct Reader {
382
    struct Reader {
383
        SharedBuffer::DataSegment& data;
383
        FragmentedSharedBuffer::DataSegment& data;
384
        size_t offset;
384
        size_t offset;
385
    } reader = { *m_data, 0 };
385
    } reader = { *m_data, 0 };
386
386
- a/Source/WebCore/platform/image-decoders/png/PNGImageDecoder.cpp -1 / +1 lines
Lines 152-158 public: a/Source/WebCore/platform/image-decoders/png/PNGImageDecoder.cpp_sec1
152
        m_readOffset = 0;
152
        m_readOffset = 0;
153
    }
153
    }
154
154
155
    bool decode(const SharedBuffer::DataSegment& data, bool sizeOnly, unsigned haltAtFrame)
155
    bool decode(const FragmentedSharedBuffer::DataSegment& data, bool sizeOnly, unsigned haltAtFrame)
156
    {
156
    {
157
        m_decodingSizeOnly = sizeOnly;
157
        m_decodingSizeOnly = sizeOnly;
158
        PNGImageDecoder* decoder = static_cast<PNGImageDecoder*>(png_get_progressive_ptr(m_png));
158
        PNGImageDecoder* decoder = static_cast<PNGImageDecoder*>(png_get_progressive_ptr(m_png));
- a/Source/WebCore/platform/image-decoders/webp/WEBPImageDecoder.cpp -2 / +2 lines
Lines 47-53 WEBPImageDecoder::WEBPImageDecoder(AlphaOption alphaOption, GammaAndColorProfile a/Source/WebCore/platform/image-decoders/webp/WEBPImageDecoder.cpp_sec1
47
47
48
WEBPImageDecoder::~WEBPImageDecoder() = default;
48
WEBPImageDecoder::~WEBPImageDecoder() = default;
49
49
50
void WEBPImageDecoder::setData(SharedBuffer& data, bool allDataReceived)
50
void WEBPImageDecoder::setData(FragmentedSharedBuffer& data, bool allDataReceived)
51
{
51
{
52
    if (failed())
52
    if (failed())
53
        return;
53
        return;
Lines 132-138 void WEBPImageDecoder::decode(size_t frameIndex, bool allDataReceived) a/Source/WebCore/platform/image-decoders/webp/WEBPImageDecoder.cpp_sec2
132
    // This can be executed both in the main thread (when not using async decoding) or in the decoding thread.
132
    // This can be executed both in the main thread (when not using async decoding) or in the decoding thread.
133
    // When executed in the decoding thread, a call to setData() from the main thread may change the data
133
    // When executed in the decoding thread, a call to setData() from the main thread may change the data
134
    // the WebPDemuxer is using, leaving it in an inconsistent state, so we need to protect the data.
134
    // the WebPDemuxer is using, leaving it in an inconsistent state, so we need to protect the data.
135
    RefPtr<SharedBuffer::DataSegment> protectedData(m_data);
135
    RefPtr<FragmentedSharedBuffer::DataSegment> protectedData(m_data);
136
    WebPData inputData = { protectedData->data(), protectedData->size() };
136
    WebPData inputData = { protectedData->data(), protectedData->size() };
137
    WebPDemuxState demuxerState;
137
    WebPDemuxState demuxerState;
138
    WebPDemuxer* demuxer = WebPDemuxPartial(&inputData, &demuxerState);
138
    WebPDemuxer* demuxer = WebPDemuxPartial(&inputData, &demuxerState);
- a/Source/WebCore/platform/image-decoders/webp/WEBPImageDecoder.h -1 / +1 lines
Lines 47-53 public: a/Source/WebCore/platform/image-decoders/webp/WEBPImageDecoder.h_sec1
47
    virtual ~WEBPImageDecoder();
47
    virtual ~WEBPImageDecoder();
48
48
49
    String filenameExtension() const override { return "webp"_s; }
49
    String filenameExtension() const override { return "webp"_s; }
50
    void setData(SharedBuffer&, bool) final;
50
    void setData(FragmentedSharedBuffer&, bool) final;
51
    ScalableImageDecoderFrame* frameBufferAtIndex(size_t index) override;
51
    ScalableImageDecoderFrame* frameBufferAtIndex(size_t index) override;
52
    RepetitionCount repetitionCount() const override;
52
    RepetitionCount repetitionCount() const override;
53
    size_t frameCount() const override { return m_frameCount; }
53
    size_t frameCount() const override { return m_frameCount; }
- a/Source/WebCore/platform/ios/PasteboardIOS.mm -3 / +3 lines
Lines 236-249 ALLOW_DEPRECATED_DECLARATIONS_BEGIN a/Source/WebCore/platform/ios/PasteboardIOS.mm_sec1
236
236
237
#if !PLATFORM(MACCATALYST)
237
#if !PLATFORM(MACCATALYST)
238
    if ([type isEqualToString:(__bridge NSString *)kUTTypeFlatRTFD]) {
238
    if ([type isEqualToString:(__bridge NSString *)kUTTypeFlatRTFD]) {
239
        RefPtr<SharedBuffer> buffer = strategy.readBufferFromPasteboard(itemIndex, kUTTypeFlatRTFD, m_pasteboardName, context());
239
        RefPtr<FragmentedSharedBuffer> buffer = strategy.readBufferFromPasteboard(itemIndex, kUTTypeFlatRTFD, m_pasteboardName, context());
240
        if (m_changeCount != changeCount())
240
        if (m_changeCount != changeCount())
241
            return ReaderResult::PasteboardWasChangedExternally;
241
            return ReaderResult::PasteboardWasChangedExternally;
242
        return buffer && reader.readRTFD(*buffer) ? ReaderResult::ReadType : ReaderResult::DidNotReadType;
242
        return buffer && reader.readRTFD(*buffer) ? ReaderResult::ReadType : ReaderResult::DidNotReadType;
243
    }
243
    }
244
244
245
    if ([type isEqualToString:(__bridge NSString *)kUTTypeRTF]) {
245
    if ([type isEqualToString:(__bridge NSString *)kUTTypeRTF]) {
246
        RefPtr<SharedBuffer> buffer = strategy.readBufferFromPasteboard(itemIndex, kUTTypeRTF, m_pasteboardName, context());
246
        RefPtr<FragmentedSharedBuffer> buffer = strategy.readBufferFromPasteboard(itemIndex, kUTTypeRTF, m_pasteboardName, context());
247
        if (m_changeCount != changeCount())
247
        if (m_changeCount != changeCount())
248
            return ReaderResult::PasteboardWasChangedExternally;
248
            return ReaderResult::PasteboardWasChangedExternally;
249
        return buffer && reader.readRTF(*buffer) ? ReaderResult::ReadType : ReaderResult::DidNotReadType;
249
        return buffer && reader.readRTF(*buffer) ? ReaderResult::ReadType : ReaderResult::DidNotReadType;
Lines 251-257 ALLOW_DEPRECATED_DECLARATIONS_BEGIN a/Source/WebCore/platform/ios/PasteboardIOS.mm_sec2
251
#endif // !PLATFORM(MACCATALYST)
251
#endif // !PLATFORM(MACCATALYST)
252
252
253
    if ([supportedImageTypes() containsObject:type]) {
253
    if ([supportedImageTypes() containsObject:type]) {
254
        RefPtr<SharedBuffer> buffer = strategy.readBufferFromPasteboard(itemIndex, type, m_pasteboardName, context());
254
        RefPtr<FragmentedSharedBuffer> buffer = strategy.readBufferFromPasteboard(itemIndex, type, m_pasteboardName, context());
255
        if (m_changeCount != changeCount())
255
        if (m_changeCount != changeCount())
256
            return ReaderResult::PasteboardWasChangedExternally;
256
            return ReaderResult::PasteboardWasChangedExternally;
257
        return buffer && reader.readImage(buffer.releaseNonNull(), type, itemInfo.preferredPresentationSize) ? ReaderResult::ReadType : ReaderResult::DidNotReadType;
257
        return buffer && reader.readImage(buffer.releaseNonNull(), type, itemInfo.preferredPresentationSize) ? ReaderResult::ReadType : ReaderResult::DidNotReadType;
- a/Source/WebCore/platform/ios/PlatformPasteboardIOS.mm -9 / +9 lines
Lines 338-344 int64_t PlatformPasteboard::setTypes(const Vector<String>&) a/Source/WebCore/platform/ios/PlatformPasteboardIOS.mm_sec1
338
    return 0;
338
    return 0;
339
}
339
}
340
340
341
int64_t PlatformPasteboard::setBufferForType(SharedBuffer*, const String&)
341
int64_t PlatformPasteboard::setBufferForType(FragmentedSharedBuffer*, const String&)
342
{
342
{
343
    return 0;
343
    return 0;
344
}
344
}
Lines 463-469 void PlatformPasteboard::write(const PasteboardWebContent& content) a/Source/WebCore/platform/ios/PlatformPasteboardIOS.mm_sec2
463
463
464
    ASSERT(content.clientTypes.size() == content.clientData.size());
464
    ASSERT(content.clientTypes.size() == content.clientData.size());
465
    for (size_t i = 0, size = content.clientTypes.size(); i < size; ++i)
465
    for (size_t i = 0, size = content.clientTypes.size(); i < size; ++i)
466
        [representationsToRegister addData:content.clientData[i]->createNSData().get() forType:content.clientTypes[i]];
466
        [representationsToRegister addData:content.clientData[i]->makeContiguous()->createNSData().get() forType:content.clientTypes[i]];
467
467
468
    if (content.dataInWebArchiveFormat) {
468
    if (content.dataInWebArchiveFormat) {
469
        auto webArchiveData = content.dataInWebArchiveFormat->createNSData();
469
        auto webArchiveData = content.dataInWebArchiveFormat->createNSData();
Lines 479-485 ALLOW_DEPRECATED_DECLARATIONS_END a/Source/WebCore/platform/ios/PlatformPasteboardIOS.mm_sec3
479
    }
479
    }
480
480
481
    if (content.dataInAttributedStringFormat) {
481
    if (content.dataInAttributedStringFormat) {
482
        if (NSAttributedString *attributedString = [NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithObject:NSAttributedString.class] fromData:content.dataInAttributedStringFormat->createNSData().get() error:nullptr])
482
        if (NSAttributedString *attributedString = [NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithObject:NSAttributedString.class] fromData:content.dataInAttributedStringFormat->makeContiguous()->createNSData().get() error:nullptr])
483
            [representationsToRegister addRepresentingObject:attributedString];
483
            [representationsToRegister addRepresentingObject:attributedString];
484
    }
484
    }
485
485
Lines 501-507 ALLOW_DEPRECATED_DECLARATIONS_END a/Source/WebCore/platform/ios/PlatformPasteboardIOS.mm_sec4
501
501
502
    PasteboardCustomData customData;
502
    PasteboardCustomData customData;
503
    customData.setOrigin(content.contentOrigin);
503
    customData.setOrigin(content.contentOrigin);
504
    [representationsToRegister addData:customData.createSharedBuffer()->createNSData().get() forType:@(PasteboardCustomData::cocoaType())];
504
    [representationsToRegister addData:customData.createSharedBuffer()->makeContiguous()->createNSData().get() forType:@(PasteboardCustomData::cocoaType())];
505
505
506
    registerItemToPasteboard(representationsToRegister.get(), m_pasteboard.get());
506
    registerItemToPasteboard(representationsToRegister.get(), m_pasteboard.get());
507
}
507
}
Lines 514-527 void PlatformPasteboard::write(const PasteboardImage& pasteboardImage) a/Source/WebCore/platform/ios/PlatformPasteboardIOS.mm_sec5
514
    auto& data = pasteboardImage.clientData;
514
    auto& data = pasteboardImage.clientData;
515
    ASSERT(types.size() == data.size());
515
    ASSERT(types.size() == data.size());
516
    for (size_t i = 0, size = types.size(); i < size; ++i)
516
    for (size_t i = 0, size = types.size(); i < size; ++i)
517
        [representationsToRegister addData:data[i]->createNSData().get() forType:types[i]];
517
        [representationsToRegister addData:data[i]->makeContiguous()->createNSData().get() forType:types[i]];
518
518
519
    if (pasteboardImage.resourceData && !pasteboardImage.resourceMIMEType.isEmpty()) {
519
    if (pasteboardImage.resourceData && !pasteboardImage.resourceMIMEType.isEmpty()) {
520
        auto utiOrMIMEType = pasteboardImage.resourceMIMEType;
520
        auto utiOrMIMEType = pasteboardImage.resourceMIMEType;
521
        if (!isDeclaredUTI(utiOrMIMEType))
521
        if (!isDeclaredUTI(utiOrMIMEType))
522
            utiOrMIMEType = UTIFromMIMEType(utiOrMIMEType);
522
            utiOrMIMEType = UTIFromMIMEType(utiOrMIMEType);
523
523
524
        auto imageData = pasteboardImage.resourceData->createNSData();
524
        auto imageData = pasteboardImage.resourceData->makeContiguous()->createNSData();
525
        [representationsToRegister addData:imageData.get() forType:(NSString *)utiOrMIMEType];
525
        [representationsToRegister addData:imageData.get() forType:(NSString *)utiOrMIMEType];
526
        [representationsToRegister setPreferredPresentationSize:pasteboardImage.imageSize];
526
        [representationsToRegister setPreferredPresentationSize:pasteboardImage.imageSize];
527
        [representationsToRegister setSuggestedName:pasteboardImage.suggestedName];
527
        [representationsToRegister setSuggestedName:pasteboardImage.suggestedName];
Lines 635-641 static RetainPtr<WebItemProviderRegistrationInfoList> createItemProviderRegistra a/Source/WebCore/platform/ios/PlatformPasteboardIOS.mm_sec6
635
    [representationsToRegister setPreferredPresentationStyle:WebPreferredPresentationStyleInline];
635
    [representationsToRegister setPreferredPresentationStyle:WebPreferredPresentationStyleInline];
636
636
637
    if (data.hasSameOriginCustomData() || !data.origin().isEmpty()) {
637
    if (data.hasSameOriginCustomData() || !data.origin().isEmpty()) {
638
        if (auto serializedSharedBuffer = data.createSharedBuffer()->createNSData()) {
638
        if (auto serializedSharedBuffer = data.createSharedBuffer()->makeContiguous()->createNSData()) {
639
            // We stash the list of supplied pasteboard types in teamData here for compatibility with drag and drop.
639
            // We stash the list of supplied pasteboard types in teamData here for compatibility with drag and drop.
640
            // Since the contents of item providers cannot be loaded prior to drop, but the pasteboard types are
640
            // Since the contents of item providers cannot be loaded prior to drop, but the pasteboard types are
641
            // contained within the custom data blob and we need to vend them to the page when firing `dragover`
641
            // contained within the custom data blob and we need to vend them to the page when firing `dragover`
Lines 672-679 ALLOW_DEPRECATED_DECLARATIONS_END a/Source/WebCore/platform/ios/PlatformPasteboardIOS.mm_sec7
672
            return;
672
            return;
673
        }
673
        }
674
674
675
        auto buffer = std::get<Ref<SharedBuffer>>(value);
675
        auto buffer = std::get<Ref<FragmentedSharedBuffer>>(value);
676
        [representationsToRegister addData:buffer->createNSData().get() forType:(NSString *)cocoaType];
676
        [representationsToRegister addData:buffer->makeContiguous()->createNSData().get() forType:(NSString *)cocoaType];
677
    });
677
    });
678
678
679
    return representationsToRegister;
679
    return representationsToRegister;
- a/Source/WebCore/platform/ios/PreviewConverterIOS.mm -1 / +1 lines
Lines 82-88 @end a/Source/WebCore/platform/ios/PreviewConverterIOS.mm_sec1
82
namespace WebCore {
82
namespace WebCore {
83
83
84
PreviewConverter::PreviewConverter(const ResourceResponse& response, PreviewConverterProvider& provider)
84
PreviewConverter::PreviewConverter(const ResourceResponse& response, PreviewConverterProvider& provider)
85
    : m_previewData { SharedBuffer::create() }
85
    : m_previewData { makeUniqueRef<SharedBufferBuilder>(FragmentedSharedBuffer::create()) }
86
    , m_originalResponse { response }
86
    , m_originalResponse { response }
87
    , m_provider { provider }
87
    , m_provider { provider }
88
    , m_platformDelegate { adoptNS([[WebPreviewConverterDelegate alloc] initWithDelegate:*this]) }
88
    , m_platformDelegate { adoptNS([[WebPreviewConverterDelegate alloc] initWithDelegate:*this]) }
- a/Source/WebCore/platform/mac/PasteboardMac.mm -2 / +2 lines
Lines 250-256 void Pasteboard::write(const Color& color) a/Source/WebCore/platform/mac/PasteboardMac.mm_sec1
250
250
251
static NSFileWrapper* fileWrapper(const PasteboardImage& pasteboardImage)
251
static NSFileWrapper* fileWrapper(const PasteboardImage& pasteboardImage)
252
{
252
{
253
    auto wrapper = adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:pasteboardImage.resourceData->createNSData().get()]);
253
    auto wrapper = adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:pasteboardImage.resourceData->makeContiguous()->createNSData().get()]);
254
    [wrapper setPreferredFilename:suggestedFilenameWithMIMEType(pasteboardImage.url.url, pasteboardImage.resourceMIMEType)];
254
    [wrapper setPreferredFilename:suggestedFilenameWithMIMEType(pasteboardImage.url.url, pasteboardImage.resourceMIMEType)];
255
    return wrapper.autorelease();
255
    return wrapper.autorelease();
256
}
256
}
Lines 362-368 void Pasteboard::read(PasteboardPlainText& text, PlainTextURLReadingPolicy allow a/Source/WebCore/platform/mac/PasteboardMac.mm_sec2
362
    
362
    
363
    if (types.contains(String(legacyRTFDPasteboardType()))) {
363
    if (types.contains(String(legacyRTFDPasteboardType()))) {
364
        if (auto data = readBufferAtPreferredItemIndex(legacyRTFDPasteboardType(), itemIndex, strategy, m_pasteboardName, context())) {
364
        if (auto data = readBufferAtPreferredItemIndex(legacyRTFDPasteboardType(), itemIndex, strategy, m_pasteboardName, context())) {
365
            if (auto attributedString = adoptNS([[NSAttributedString alloc] initWithRTFD:data->createNSData().get() documentAttributes:nil])) {
365
            if (auto attributedString = adoptNS([[NSAttributedString alloc] initWithRTFD:data->makeContiguous()->createNSData().get() documentAttributes:nil])) {
366
                text.text = [attributedString string];
366
                text.text = [attributedString string];
367
                text.isURL = false;
367
                text.isURL = false;
368
                return;
368
                return;
- a/Source/WebCore/platform/mac/PasteboardWriter.mm -2 / +2 lines
Lines 128-138 ALLOW_DEPRECATED_DECLARATIONS_END a/Source/WebCore/platform/mac/PasteboardWriter.mm_sec1
128
            [pasteboardItem setString:webContent->dataInStringFormat forType:NSPasteboardTypeString];
128
            [pasteboardItem setString:webContent->dataInStringFormat forType:NSPasteboardTypeString];
129
129
130
        for (unsigned i = 0; i < webContent->clientTypes.size(); ++i)
130
        for (unsigned i = 0; i < webContent->clientTypes.size(); ++i)
131
            [pasteboardItem setData:webContent->clientData[i]->createNSData().get() forType:toUTIUnlessAlreadyUTI(webContent->clientTypes[i]).get()];
131
            [pasteboardItem setData:webContent->clientData[i]->makeContiguous()->createNSData().get() forType:toUTIUnlessAlreadyUTI(webContent->clientTypes[i]).get()];
132
132
133
        PasteboardCustomData customData;
133
        PasteboardCustomData customData;
134
        customData.setOrigin(webContent->contentOrigin);
134
        customData.setOrigin(webContent->contentOrigin);
135
        [pasteboardItem setData:customData.createSharedBuffer()->createNSData().get() forType:toUTIUnlessAlreadyUTI(String(PasteboardCustomData::cocoaType())).get()];
135
        [pasteboardItem setData:customData.createSharedBuffer()->makeContiguous()->createNSData().get() forType:toUTIUnlessAlreadyUTI(String(PasteboardCustomData::cocoaType())).get()];
136
    }
136
    }
137
137
138
    return pasteboardItem;
138
    return pasteboardItem;
- a/Source/WebCore/platform/mac/PlatformPasteboardMac.mm -7 / +7 lines
Lines 263-270 int64_t PlatformPasteboard::write(const PasteboardCustomData& data) a/Source/WebCore/platform/mac/PlatformPasteboardMac.mm_sec1
263
        if (platformType.isEmpty())
263
        if (platformType.isEmpty())
264
            return;
264
            return;
265
265
266
        if (std::holds_alternative<Ref<SharedBuffer>>(stringOrBuffer)) {
266
        if (std::holds_alternative<Ref<FragmentedSharedBuffer>>(stringOrBuffer)) {
267
            if (auto platformData = std::get<Ref<SharedBuffer>>(stringOrBuffer)->createNSData())
267
            if (auto platformData = std::get<Ref<FragmentedSharedBuffer>>(stringOrBuffer)->makeContiguous()->createNSData())
268
                [m_pasteboard setData:platformData.get() forType:platformType];
268
                [m_pasteboard setData:platformData.get() forType:platformType];
269
        } else if (std::holds_alternative<String>(stringOrBuffer)) {
269
        } else if (std::holds_alternative<String>(stringOrBuffer)) {
270
            auto string = std::get<String>(stringOrBuffer);
270
            auto string = std::get<String>(stringOrBuffer);
Lines 274-280 int64_t PlatformPasteboard::write(const PasteboardCustomData& data) a/Source/WebCore/platform/mac/PlatformPasteboardMac.mm_sec2
274
    });
274
    });
275
275
276
    if (shouldWriteCustomData) {
276
    if (shouldWriteCustomData) {
277
        if (auto serializedCustomData = data.createSharedBuffer()->createNSData())
277
        if (auto serializedCustomData = data.createSharedBuffer()->makeContiguous()->createNSData())
278
            [m_pasteboard setData:serializedCustomData.get() forType:@(PasteboardCustomData::cocoaType())];
278
            [m_pasteboard setData:serializedCustomData.get() forType:@(PasteboardCustomData::cocoaType())];
279
    }
279
    }
280
280
Lines 341-352 int64_t PlatformPasteboard::setTypes(const Vector<String>& pasteboardTypes) a/Source/WebCore/platform/mac/PlatformPasteboardMac.mm_sec3
341
    return [m_pasteboard declareTypes:createNSArray(pasteboardTypes).get() owner:nil];
341
    return [m_pasteboard declareTypes:createNSArray(pasteboardTypes).get() owner:nil];
342
}
342
}
343
343
344
int64_t PlatformPasteboard::setBufferForType(SharedBuffer* buffer, const String& pasteboardType)
344
int64_t PlatformPasteboard::setBufferForType(FragmentedSharedBuffer* buffer, const String& pasteboardType)
345
{
345
{
346
    if (!canWritePasteboardType(pasteboardType))
346
    if (!canWritePasteboardType(pasteboardType))
347
        return 0;
347
        return 0;
348
348
349
    BOOL didWriteData = [m_pasteboard setData:buffer ? buffer->createNSData().get() : nil forType:pasteboardType];
349
    BOOL didWriteData = [m_pasteboard setData:buffer ? buffer->makeContiguous()->createNSData().get() : nil forType:pasteboardType];
350
    if (!didWriteData)
350
    if (!didWriteData)
351
        return 0;
351
        return 0;
352
    return changeCount();
352
    return changeCount();
Lines 504-511 static RetainPtr<NSPasteboardItem> createPasteboardItem(const PasteboardCustomDa a/Source/WebCore/platform/mac/PlatformPasteboardMac.mm_sec4
504
        if (!platformType)
504
        if (!platformType)
505
            return;
505
            return;
506
506
507
        if (std::holds_alternative<Ref<SharedBuffer>>(stringOrBuffer)) {
507
        if (std::holds_alternative<Ref<FragmentedSharedBuffer>>(stringOrBuffer)) {
508
            if (auto platformData = std::get<Ref<SharedBuffer>>(stringOrBuffer)->createNSData())
508
            if (auto platformData = std::get<Ref<FragmentedSharedBuffer>>(stringOrBuffer)->makeContiguous()->createNSData())
509
                [item setData:platformData.get() forType:platformType];
509
                [item setData:platformData.get() forType:platformType];
510
        } else if (std::holds_alternative<String>(stringOrBuffer)) {
510
        } else if (std::holds_alternative<String>(stringOrBuffer)) {
511
            auto string = std::get<String>(stringOrBuffer);
511
            auto string = std::get<String>(stringOrBuffer);
- a/Source/WebCore/platform/mediarecorder/MediaRecorderPrivate.h -2 / +2 lines
Lines 43-49 class MediaSample; a/Source/WebCore/platform/mediarecorder/MediaRecorderPrivate.h_sec1
43
class MediaStreamPrivate;
43
class MediaStreamPrivate;
44
class MediaStreamTrackPrivate;
44
class MediaStreamTrackPrivate;
45
class PlatformAudioData;
45
class PlatformAudioData;
46
class SharedBuffer;
46
class FragmentedSharedBuffer;
47
47
48
struct MediaRecorderPrivateOptions;
48
struct MediaRecorderPrivateOptions;
49
49
Lines 59-65 public: a/Source/WebCore/platform/mediarecorder/MediaRecorderPrivate.h_sec2
59
    };
59
    };
60
    WEBCORE_EXPORT static AudioVideoSelectedTracks selectTracks(MediaStreamPrivate&);
60
    WEBCORE_EXPORT static AudioVideoSelectedTracks selectTracks(MediaStreamPrivate&);
61
61
62
    using FetchDataCallback = CompletionHandler<void(RefPtr<SharedBuffer>&&, const String& mimeType, double)>;
62
    using FetchDataCallback = CompletionHandler<void(RefPtr<FragmentedSharedBuffer>&&, const String& mimeType, double)>;
63
    virtual void fetchData(FetchDataCallback&&) = 0;
63
    virtual void fetchData(FetchDataCallback&&) = 0;
64
    virtual const String& mimeType() const = 0;
64
    virtual const String& mimeType() const = 0;
65
65
- a/Source/WebCore/platform/mediarecorder/MediaRecorderPrivateMock.cpp -1 / +1 lines
Lines 93-99 void MediaRecorderPrivateMock::generateMockCounterString() a/Source/WebCore/platform/mediarecorder/MediaRecorderPrivateMock.cpp_sec1
93
93
94
void MediaRecorderPrivateMock::fetchData(FetchDataCallback&& completionHandler)
94
void MediaRecorderPrivateMock::fetchData(FetchDataCallback&& completionHandler)
95
{
95
{
96
    RefPtr<SharedBuffer> buffer;
96
    RefPtr<FragmentedSharedBuffer> buffer;
97
    {
97
    {
98
        Locker locker { m_bufferLock };
98
        Locker locker { m_bufferLock };
99
        Vector<uint8_t> value { m_buffer.characters8(), m_buffer.length() };
99
        Vector<uint8_t> value { m_buffer.characters8(), m_buffer.length() };
- a/Source/WebCore/platform/mediarecorder/cocoa/MediaRecorderPrivateWriterCocoa.h -4 / +4 lines
Lines 70-76 public: a/Source/WebCore/platform/mediarecorder/cocoa/MediaRecorderPrivateWriterCocoa.h_sec1
70
    void appendVideoSampleBuffer(MediaSample&);
70
    void appendVideoSampleBuffer(MediaSample&);
71
    void appendAudioSampleBuffer(const PlatformAudioData&, const AudioStreamDescription&, const WTF::MediaTime&, size_t);
71
    void appendAudioSampleBuffer(const PlatformAudioData&, const AudioStreamDescription&, const WTF::MediaTime&, size_t);
72
    void stopRecording();
72
    void stopRecording();
73
    void fetchData(CompletionHandler<void(RefPtr<SharedBuffer>&&, double)>&&);
73
    void fetchData(CompletionHandler<void(RefPtr<FragmentedSharedBuffer>&&, double)>&&);
74
74
75
    void pause();
75
    void pause();
76
    void resume();
76
    void resume();
Lines 105-111 private: a/Source/WebCore/platform/mediarecorder/cocoa/MediaRecorderPrivateWriterCocoa.h_sec2
105
105
106
    void finishedFlushingSamples();
106
    void finishedFlushingSamples();
107
    void completeFetchData();
107
    void completeFetchData();
108
    RefPtr<SharedBuffer> takeData();
108
    RefPtr<FragmentedSharedBuffer> takeData();
109
109
110
    bool m_hasAudio { false };
110
    bool m_hasAudio { false };
111
    bool m_hasVideo { false };
111
    bool m_hasVideo { false };
Lines 117-124 private: a/Source/WebCore/platform/mediarecorder/cocoa/MediaRecorderPrivateWriterCocoa.h_sec3
117
    RetainPtr<AVAssetWriter> m_writer;
117
    RetainPtr<AVAssetWriter> m_writer;
118
118
119
    Lock m_dataLock;
119
    Lock m_dataLock;
120
    RefPtr<SharedBuffer> m_data WTF_GUARDED_BY_LOCK(m_dataLock);
120
    SharedBufferBuilder m_data WTF_GUARDED_BY_LOCK(m_dataLock);
121
    CompletionHandler<void(RefPtr<SharedBuffer>&&, double)> m_fetchDataCompletionHandler;
121
    CompletionHandler<void(RefPtr<FragmentedSharedBuffer>&&, double)> m_fetchDataCompletionHandler;
122
122
123
    RetainPtr<CMFormatDescriptionRef> m_audioFormatDescription;
123
    RetainPtr<CMFormatDescriptionRef> m_audioFormatDescription;
124
    std::unique_ptr<AudioSampleBufferCompressor> m_audioCompressor;
124
    std::unique_ptr<AudioSampleBufferCompressor> m_audioCompressor;
- a/Source/WebCore/platform/mediarecorder/cocoa/MediaRecorderPrivateWriterCocoa.mm -11 / +4 lines
Lines 137-146 MediaRecorderPrivateWriter::~MediaRecorderPrivateWriter() a/Source/WebCore/platform/mediarecorder/cocoa/MediaRecorderPrivateWriterCocoa.mm_sec1
137
        m_writer.clear();
137
        m_writer.clear();
138
    }
138
    }
139
139
140
    // At this pointer, we should no longer be writing any data, so it should be safe to close and nullify m_data without locking.
141
    if (m_writerDelegate)
140
    if (m_writerDelegate)
142
        [m_writerDelegate close];
141
        [m_writerDelegate close];
143
    m_data = nullptr;
144
142
145
    if (auto completionHandler = WTFMove(m_fetchDataCompletionHandler))
143
    if (auto completionHandler = WTFMove(m_fetchDataCompletionHandler))
146
        completionHandler(nullptr, 0);
144
        completionHandler(nullptr, 0);
Lines 495-501 void MediaRecorderPrivateWriter::stopRecording() a/Source/WebCore/platform/mediarecorder/cocoa/MediaRecorderPrivateWriterCocoa.mm_sec2
495
    });
493
    });
496
}
494
}
497
495
498
void MediaRecorderPrivateWriter::fetchData(CompletionHandler<void(RefPtr<SharedBuffer>&&, double)>&& completionHandler)
496
void MediaRecorderPrivateWriter::fetchData(CompletionHandler<void(RefPtr<FragmentedSharedBuffer>&&, double)>&& completionHandler)
499
{
497
{
500
    m_fetchDataCompletionHandler = WTFMove(completionHandler);
498
    m_fetchDataCompletionHandler = WTFMove(completionHandler);
501
499
Lines 537-554 void MediaRecorderPrivateWriter::completeFetchData() a/Source/WebCore/platform/mediarecorder/cocoa/MediaRecorderPrivateWriterCocoa.mm_sec3
537
void MediaRecorderPrivateWriter::appendData(const uint8_t* data, size_t size)
535
void MediaRecorderPrivateWriter::appendData(const uint8_t* data, size_t size)
538
{
536
{
539
    Locker locker { m_dataLock };
537
    Locker locker { m_dataLock };
540
    if (!m_data) {
538
    m_data.append(data, size);
541
        m_data = SharedBuffer::create(data, size);
542
        return;
543
    }
544
    m_data->append(data, size);
545
}
539
}
546
540
547
RefPtr<SharedBuffer> MediaRecorderPrivateWriter::takeData()
541
RefPtr<FragmentedSharedBuffer> MediaRecorderPrivateWriter::takeData()
548
{
542
{
549
    Locker locker { m_dataLock };
543
    Locker locker { m_dataLock };
550
    auto data = WTFMove(m_data);
544
    return m_data.take();
551
    return data;
552
}
545
}
553
546
554
void MediaRecorderPrivateWriter::pause()
547
void MediaRecorderPrivateWriter::pause()
- a/Source/WebCore/platform/network/DataURLDecoder.h -1 / +1 lines
Lines 33-39 a/Source/WebCore/platform/network/DataURLDecoder.h_sec1
33
33
34
namespace WebCore {
34
namespace WebCore {
35
35
36
class SharedBuffer;
36
class FragmentedSharedBuffer;
37
37
38
namespace DataURLDecoder {
38
namespace DataURLDecoder {
39
39
- a/Source/WebCore/platform/network/ResourceHandle.h -1 / +1 lines
Lines 84-90 class NetworkLoadMetrics; a/Source/WebCore/platform/network/ResourceHandle.h_sec1
84
class ResourceRequest;
84
class ResourceRequest;
85
class ResourceResponse;
85
class ResourceResponse;
86
class SecurityOrigin;
86
class SecurityOrigin;
87
class SharedBuffer;
87
class FragmentedSharedBuffer;
88
class SynchronousLoaderMessageQueue;
88
class SynchronousLoaderMessageQueue;
89
class Timer;
89
class Timer;
90
90
- a/Source/WebCore/platform/network/ResourceHandleClient.cpp -2 / +2 lines
Lines 36-44 ResourceHandleClient::ResourceHandleClient() = default; a/Source/WebCore/platform/network/ResourceHandleClient.cpp_sec1
36
36
37
ResourceHandleClient::~ResourceHandleClient() = default;
37
ResourceHandleClient::~ResourceHandleClient() = default;
38
38
39
void ResourceHandleClient::didReceiveBuffer(ResourceHandle* handle, Ref<SharedBuffer>&& buffer, int encodedDataLength)
39
void ResourceHandleClient::didReceiveBuffer(ResourceHandle* handle, Ref<FragmentedSharedBuffer>&& buffer, int encodedDataLength)
40
{
40
{
41
    didReceiveData(handle, buffer->data(), buffer->size(), encodedDataLength);
41
    didReceiveData(handle, buffer->makeContiguous()->data(), buffer->size(), encodedDataLength);
42
}
42
}
43
43
44
}
44
}
- a/Source/WebCore/platform/network/ResourceHandleClient.h -2 / +2 lines
Lines 50-56 class ResourceHandle; a/Source/WebCore/platform/network/ResourceHandleClient.h_sec1
50
class ResourceError;
50
class ResourceError;
51
class ResourceRequest;
51
class ResourceRequest;
52
class ResourceResponse;
52
class ResourceResponse;
53
class SharedBuffer;
53
class FragmentedSharedBuffer;
54
54
55
enum CacheStoragePolicy {
55
enum CacheStoragePolicy {
56
    StorageAllowed,
56
    StorageAllowed,
Lines 66-72 public: a/Source/WebCore/platform/network/ResourceHandleClient.h_sec2
66
    virtual void didSendData(ResourceHandle*, unsigned long long /*bytesSent*/, unsigned long long /*totalBytesToBeSent*/) { }
66
    virtual void didSendData(ResourceHandle*, unsigned long long /*bytesSent*/, unsigned long long /*totalBytesToBeSent*/) { }
67
67
68
    virtual void didReceiveData(ResourceHandle*, const uint8_t*, unsigned, int /*encodedDataLength*/) { }
68
    virtual void didReceiveData(ResourceHandle*, const uint8_t*, unsigned, int /*encodedDataLength*/) { }
69
    WEBCORE_EXPORT virtual void didReceiveBuffer(ResourceHandle*, Ref<SharedBuffer>&&, int encodedDataLength);
69
    WEBCORE_EXPORT virtual void didReceiveBuffer(ResourceHandle*, Ref<FragmentedSharedBuffer>&&, int encodedDataLength);
70
    
70
    
71
    virtual void didFinishLoading(ResourceHandle*, const NetworkLoadMetrics&) { }
71
    virtual void didFinishLoading(ResourceHandle*, const NetworkLoadMetrics&) { }
72
    virtual void didFail(ResourceHandle*, const ResourceError&) { }
72
    virtual void didFail(ResourceHandle*, const ResourceError&) { }
- a/Source/WebCore/platform/network/cocoa/RangeResponseGenerator.mm -13 / +12 lines
Lines 41-48 namespace WebCore { a/Source/WebCore/platform/network/cocoa/RangeResponseGenerator.mm_sec1
41
struct RangeResponseGenerator::Data {
41
struct RangeResponseGenerator::Data {
42
    WTF_MAKE_STRUCT_FAST_ALLOCATED;
42
    WTF_MAKE_STRUCT_FAST_ALLOCATED;
43
    Data(const ResourceResponse& response, PlatformMediaResource& resource)
43
    Data(const ResourceResponse& response, PlatformMediaResource& resource)
44
        : buffer(SharedBuffer::create())
44
        : originalResponse(response)
45
        , originalResponse(response)
46
        , resource(&resource) { }
45
        , resource(&resource) { }
47
46
48
    struct TaskData : public CanMakeWeakPtr<TaskData> {
47
    struct TaskData : public CanMakeWeakPtr<TaskData> {
Lines 55-63 struct RangeResponseGenerator::Data { a/Source/WebCore/platform/network/cocoa/RangeResponseGenerator.mm_sec2
55
        size_t nextByteToGiveBufferIndex { 0 };
54
        size_t nextByteToGiveBufferIndex { 0 };
56
        enum class ResponseState : uint8_t { NotSynthesizedYet, WaitingForSession, SessionCalledCompletionHandler } responseState { ResponseState::NotSynthesizedYet };
55
        enum class ResponseState : uint8_t { NotSynthesizedYet, WaitingForSession, SessionCalledCompletionHandler } responseState { ResponseState::NotSynthesizedYet };
57
    };
56
    };
58
    
57
59
    HashMap<RetainPtr<WebCoreNSURLSessionDataTask>, std::unique_ptr<TaskData>> taskData;
58
    HashMap<RetainPtr<WebCoreNSURLSessionDataTask>, std::unique_ptr<TaskData>> taskData;
60
    Ref<SharedBuffer> buffer;
59
    SharedBufferBuilder buffer;
61
    ResourceResponse originalResponse;
60
    ResourceResponse originalResponse;
62
    enum class SuccessfullyFinishedLoading : bool { No, Yes } successfullyFinishedLoading { SuccessfullyFinishedLoading::No };
61
    enum class SuccessfullyFinishedLoading : bool { No, Yes } successfullyFinishedLoading { SuccessfullyFinishedLoading::No };
63
    RefPtr<PlatformMediaResource> resource;
62
    RefPtr<PlatformMediaResource> resource;
Lines 106-127 void RangeResponseGenerator::removeTask(WebCoreNSURLSessionDataTask *task) a/Source/WebCore/platform/network/cocoa/RangeResponseGenerator.mm_sec3
106
void RangeResponseGenerator::giveResponseToTaskIfBytesInRangeReceived(WebCoreNSURLSessionDataTask *task, const ParsedRequestRange& range, std::optional<size_t> expectedContentLength, const Data& data)
105
void RangeResponseGenerator::giveResponseToTaskIfBytesInRangeReceived(WebCoreNSURLSessionDataTask *task, const ParsedRequestRange& range, std::optional<size_t> expectedContentLength, const Data& data)
107
{
106
{
108
    ASSERT(isMainThread());
107
    ASSERT(isMainThread());
109
    auto buffer = data.buffer;
110
    auto bufferSize = buffer->size();
111
108
112
    // FIXME: We ought to be able to just make a range with a * after the / but AVFoundation doesn't accept such ranges.
109
    // FIXME: We ought to be able to just make a range with a * after the / but AVFoundation doesn't accept such ranges.
113
    // Instead, we just wait until the load has completed, at which time we will know the content length from the buffer length.
110
    // Instead, we just wait until the load has completed, at which time we will know the content length from the buffer length.
114
    if (!expectedContentLength)
111
    if (!expectedContentLength)
115
        return;
112
        return;
116
113
114
    auto bufferSize = data.buffer.size();
117
    if (bufferSize < range.begin)
115
    if (bufferSize < range.begin)
118
        return;
116
        return;
119
    
117
118
    auto buffer = data.buffer.get();
120
    auto* taskData = data.taskData.get(task);
119
    auto* taskData = data.taskData.get(task);
121
    if (!taskData)
120
    if (!taskData)
122
        return;
121
        return;
123
    
122
124
    auto giveBytesToTask = [task = retainPtr(task), buffer, taskData = WeakPtr { *taskData }, generator = WeakPtr { *this }] {
123
    auto giveBytesToTask = [task = retainPtr(task), buffer, bufferSize, taskData = WeakPtr { *taskData }, generator = WeakPtr { *this }] {
125
        ASSERT(isMainThread());
124
        ASSERT(isMainThread());
126
        if ([task state] != NSURLSessionTaskStateRunning)
125
        if ([task state] != NSURLSessionTaskStateRunning)
127
            return;
126
            return;
Lines 130-136 void RangeResponseGenerator::giveResponseToTaskIfBytesInRangeReceived(WebCoreNSU a/Source/WebCore/platform/network/cocoa/RangeResponseGenerator.mm_sec4
130
        auto& range = taskData->range;
129
        auto& range = taskData->range;
131
        auto& byteIndex = taskData->nextByteToGiveBufferIndex;
130
        auto& byteIndex = taskData->nextByteToGiveBufferIndex;
132
        while (true) {
131
        while (true) {
133
            if (byteIndex >= buffer->size())
132
            if (byteIndex >= bufferSize)
134
                break;
133
                break;
135
            auto bufferView = buffer->getSomeData(byteIndex);
134
            auto bufferView = buffer->getSomeData(byteIndex);
136
            if (!bufferView.size() || byteIndex > range.end)
135
            if (!bufferView.size() || byteIndex > range.end)
Lines 175-181 std::optional<size_t> RangeResponseGenerator::expectedContentLengthFromData(cons a/Source/WebCore/platform/network/cocoa/RangeResponseGenerator.mm_sec5
175
{
174
{
176
    ASSERT(isMainThread());
175
    ASSERT(isMainThread());
177
    if (data.successfullyFinishedLoading == Data::SuccessfullyFinishedLoading::Yes)
176
    if (data.successfullyFinishedLoading == Data::SuccessfullyFinishedLoading::Yes)
178
        return data.buffer->size();
177
        return data.buffer.size();
179
178
180
    // FIXME: ResourceResponseBase::expectedContentLength() should return std::optional<size_t> instead of us doing this check here.
179
    // FIXME: ResourceResponseBase::expectedContentLength() should return std::optional<size_t> instead of us doing this check here.
181
    auto expectedContentLength = data.originalResponse.expectedContentLength();
180
    auto expectedContentLength = data.originalResponse.expectedContentLength();
Lines 244-250 private: a/Source/WebCore/platform/network/cocoa/RangeResponseGenerator.mm_sec6
244
        return false;
243
        return false;
245
    }
244
    }
246
245
247
    void dataReceived(PlatformMediaResource&, Ref<SharedBuffer>&& buffer) final
246
    void dataReceived(PlatformMediaResource&, Ref<FragmentedSharedBuffer>&& buffer) final
248
    {
247
    {
249
        ASSERT(isMainThread());
248
        ASSERT(isMainThread());
250
        if (!m_generator)
249
        if (!m_generator)
Lines 252-258 private: a/Source/WebCore/platform/network/cocoa/RangeResponseGenerator.mm_sec7
252
        auto* data = m_generator->m_map.get(m_urlString);
251
        auto* data = m_generator->m_map.get(m_urlString);
253
        if (!data)
252
        if (!data)
254
            return;
253
            return;
255
        data->buffer->append(WTFMove(buffer));
254
        data->buffer.append(WTFMove(buffer));
256
        m_generator->giveResponseToTasksWithFinishedRanges(*data);
255
        m_generator->giveResponseToTasksWithFinishedRanges(*data);
257
    }
256
    }
258
257
- a/Source/WebCore/platform/network/cocoa/WebCoreNSURLSession.h -2 / +2 lines
Lines 50-56 class PlatformMediaResourceLoader; a/Source/WebCore/platform/network/cocoa/WebCoreNSURLSession.h_sec1
50
class ResourceError;
50
class ResourceError;
51
class ResourceRequest;
51
class ResourceRequest;
52
class ResourceResponse;
52
class ResourceResponse;
53
class SharedBuffer;
53
class FragmentedSharedBuffer;
54
class SharedBufferDataView;
54
class SharedBufferDataView;
55
class WebCoreNSURLSessionDataTaskClient;
55
class WebCoreNSURLSessionDataTaskClient;
56
enum class ShouldContinuePolicyCheck : bool;
56
enum class ShouldContinuePolicyCheck : bool;
Lines 158-164 WEBCORE_EXPORT @interface WebCoreNSURLSession : NSObject { a/Source/WebCore/platform/network/cocoa/WebCoreNSURLSession.h_sec2
158
- (void)resource:(nullable WebCore::PlatformMediaResource*)resource sentBytes:(unsigned long long)bytesSent totalBytesToBeSent:(unsigned long long)totalBytesToBeSent;
158
- (void)resource:(nullable WebCore::PlatformMediaResource*)resource sentBytes:(unsigned long long)bytesSent totalBytesToBeSent:(unsigned long long)totalBytesToBeSent;
159
- (void)resource:(nullable WebCore::PlatformMediaResource*)resource receivedResponse:(const WebCore::ResourceResponse&)response completionHandler:(CompletionHandler<void(WebCore::ShouldContinuePolicyCheck)>&&)completionHandler;
159
- (void)resource:(nullable WebCore::PlatformMediaResource*)resource receivedResponse:(const WebCore::ResourceResponse&)response completionHandler:(CompletionHandler<void(WebCore::ShouldContinuePolicyCheck)>&&)completionHandler;
160
- (BOOL)resource:(nullable WebCore::PlatformMediaResource*)resource shouldCacheResponse:(const WebCore::ResourceResponse&)response;
160
- (BOOL)resource:(nullable WebCore::PlatformMediaResource*)resource shouldCacheResponse:(const WebCore::ResourceResponse&)response;
161
- (void)resource:(nullable WebCore::PlatformMediaResource*)resource receivedData:(Ref<WebCore::SharedBuffer>&&)data;
161
- (void)resource:(nullable WebCore::PlatformMediaResource*)resource receivedData:(Ref<WebCore::FragmentedSharedBuffer>&&)data;
162
- (void)resource:(nullable WebCore::PlatformMediaResource*)resource receivedRedirect:(const WebCore::ResourceResponse&)response request:(WebCore::ResourceRequest&&)request completionHandler:(CompletionHandler<void(WebCore::ResourceRequest&&)>&&)completionHandler;
162
- (void)resource:(nullable WebCore::PlatformMediaResource*)resource receivedRedirect:(const WebCore::ResourceResponse&)response request:(WebCore::ResourceRequest&&)request completionHandler:(CompletionHandler<void(WebCore::ResourceRequest&&)>&&)completionHandler;
163
- (void)resource:(nullable WebCore::PlatformMediaResource*)resource accessControlCheckFailedWithError:(const WebCore::ResourceError&)error;
163
- (void)resource:(nullable WebCore::PlatformMediaResource*)resource accessControlCheckFailedWithError:(const WebCore::ResourceError&)error;
164
- (void)resource:(nullable WebCore::PlatformMediaResource*)resource loadFailedWithError:(const WebCore::ResourceError&)error;
164
- (void)resource:(nullable WebCore::PlatformMediaResource*)resource loadFailedWithError:(const WebCore::ResourceError&)error;
- a/Source/WebCore/platform/network/cocoa/WebCoreNSURLSession.mm -4 / +4 lines
Lines 608-614 public: a/Source/WebCore/platform/network/cocoa/WebCoreNSURLSession.mm_sec1
608
    void redirectReceived(PlatformMediaResource&, ResourceRequest&&, const ResourceResponse&, CompletionHandler<void(ResourceRequest&&)>&&) override;
608
    void redirectReceived(PlatformMediaResource&, ResourceRequest&&, const ResourceResponse&, CompletionHandler<void(ResourceRequest&&)>&&) override;
609
    bool shouldCacheResponse(PlatformMediaResource&, const ResourceResponse&) override;
609
    bool shouldCacheResponse(PlatformMediaResource&, const ResourceResponse&) override;
610
    void dataSent(PlatformMediaResource&, unsigned long long, unsigned long long) override;
610
    void dataSent(PlatformMediaResource&, unsigned long long, unsigned long long) override;
611
    void dataReceived(PlatformMediaResource&, Ref<SharedBuffer>&&) override;
611
    void dataReceived(PlatformMediaResource&, Ref<FragmentedSharedBuffer>&&) override;
612
    void accessControlCheckFailed(PlatformMediaResource&, const ResourceError&) override;
612
    void accessControlCheckFailed(PlatformMediaResource&, const ResourceError&) override;
613
    void loadFailed(PlatformMediaResource&, const ResourceError&) override;
613
    void loadFailed(PlatformMediaResource&, const ResourceError&) override;
614
    void loadFinished(PlatformMediaResource&, const NetworkLoadMetrics&) override;
614
    void loadFinished(PlatformMediaResource&, const NetworkLoadMetrics&) override;
Lines 652-658 bool WebCoreNSURLSessionDataTaskClient::shouldCacheResponse(PlatformMediaResourc a/Source/WebCore/platform/network/cocoa/WebCoreNSURLSession.mm_sec2
652
    return [m_task resource:&resource shouldCacheResponse:response];
652
    return [m_task resource:&resource shouldCacheResponse:response];
653
}
653
}
654
654
655
void WebCoreNSURLSessionDataTaskClient::dataReceived(PlatformMediaResource& resource, Ref<SharedBuffer>&& buffer)
655
void WebCoreNSURLSessionDataTaskClient::dataReceived(PlatformMediaResource& resource, Ref<FragmentedSharedBuffer>&& buffer)
656
{
656
{
657
    Locker locker { m_taskLock };
657
    Locker locker { m_taskLock };
658
    if (!m_task)
658
    if (!m_task)
Lines 915-925 - (BOOL)resource:(PlatformMediaResource*)resource shouldCacheResponse:(const Res a/Source/WebCore/platform/network/cocoa/WebCoreNSURLSession.mm_sec3
915
    return response.httpHeaderField(HTTPHeaderName::ContentRange).isEmpty();
915
    return response.httpHeaderField(HTTPHeaderName::ContentRange).isEmpty();
916
}
916
}
917
917
918
- (void)resource:(PlatformMediaResource*)resource receivedData:(Ref<WebCore::SharedBuffer>&&)data
918
- (void)resource:(PlatformMediaResource*)resource receivedData:(Ref<WebCore::FragmentedSharedBuffer>&&)data
919
{
919
{
920
    ASSERT_UNUSED(resource, !resource || resource == _resource);
920
    ASSERT_UNUSED(resource, !resource || resource == _resource);
921
    [self.session addDelegateOperation:[strongSelf = RetainPtr { self }, data = WTFMove(data)] {
921
    [self.session addDelegateOperation:[strongSelf = RetainPtr { self }, data = WTFMove(data)] {
922
        auto nsData = data->createNSData();
922
        auto nsData = data->makeContiguous()->createNSData();
923
        strongSelf.get().countOfBytesReceived += data->size();
923
        strongSelf.get().countOfBytesReceived += data->size();
924
        id<NSURLSessionDataDelegate> dataDelegate = (id<NSURLSessionDataDelegate>)strongSelf.get().session.delegate;
924
        id<NSURLSessionDataDelegate> dataDelegate = (id<NSURLSessionDataDelegate>)strongSelf.get().session.delegate;
925
        if ([dataDelegate respondsToSelector:@selector(URLSession:dataTask:didReceiveData:)])
925
        if ([dataDelegate respondsToSelector:@selector(URLSession:dataTask:didReceiveData:)])
- a/Source/WebCore/platform/network/curl/CurlDownload.cpp -1 / +1 lines
Lines 103-109 void CurlDownload::curlDidReceiveResponse(CurlRequest& request, CurlResponse&& r a/Source/WebCore/platform/network/curl/CurlDownload.cpp_sec1
103
}
103
}
104
104
105
105
106
void CurlDownload::curlDidReceiveBuffer(CurlRequest&, Ref<SharedBuffer>&& buffer)
106
void CurlDownload::curlDidReceiveBuffer(CurlRequest&, Ref<FragmentedSharedBuffer>&& buffer)
107
{
107
{
108
    ASSERT(isMainThread());
108
    ASSERT(isMainThread());
109
109
- a/Source/WebCore/platform/network/curl/CurlDownload.h -1 / +1 lines
Lines 72-78 private: a/Source/WebCore/platform/network/curl/CurlDownload.h_sec1
72
    Ref<CurlRequest> createCurlRequest(ResourceRequest&);
72
    Ref<CurlRequest> createCurlRequest(ResourceRequest&);
73
    void curlDidSendData(CurlRequest&, unsigned long long, unsigned long long) override { }
73
    void curlDidSendData(CurlRequest&, unsigned long long, unsigned long long) override { }
74
    void curlDidReceiveResponse(CurlRequest&, CurlResponse&&) override;
74
    void curlDidReceiveResponse(CurlRequest&, CurlResponse&&) override;
75
    void curlDidReceiveBuffer(CurlRequest&, Ref<SharedBuffer>&&) override;
75
    void curlDidReceiveBuffer(CurlRequest&, Ref<FragmentedSharedBuffer>&&) override;
76
    void curlDidComplete(CurlRequest&, NetworkLoadMetrics&&) override;
76
    void curlDidComplete(CurlRequest&, NetworkLoadMetrics&&) override;
77
    void curlDidFailWithError(CurlRequest&, ResourceError&&, CertificateInfo&&) override;
77
    void curlDidFailWithError(CurlRequest&, ResourceError&&, CertificateInfo&&) override;
78
78
- a/Source/WebCore/platform/network/curl/CurlMultipartHandle.cpp -3 / +3 lines
Lines 119-130 CurlMultipartHandle::CurlMultipartHandle(CurlMultipartHandleClient& client, cons a/Source/WebCore/platform/network/curl/CurlMultipartHandle.cpp_sec1
119
119
120
}
120
}
121
121
122
void CurlMultipartHandle::didReceiveData(const SharedBuffer& buffer)
122
void CurlMultipartHandle::didReceiveData(const FragmentedSharedBuffer& buffer)
123
{
123
{
124
    if (m_state == State::End)
124
    if (m_state == State::End)
125
        return; // The handler is closed down so ignore everything.
125
        return; // The handler is closed down so ignore everything.
126
126
127
    m_buffer.append(buffer.data(), buffer.size());
127
    m_buffer.append(buffer.makeContiguous()->data(), buffer.size());
128
128
129
    while (processContent()) { }
129
    while (processContent()) { }
130
}
130
}
Lines 137-143 void CurlMultipartHandle::didComplete() a/Source/WebCore/platform/network/curl/CurlMultipartHandle.cpp_sec2
137
    if (m_state != State::End) {
137
    if (m_state != State::End) {
138
        // It seems we are still not at the end of the processing.
138
        // It seems we are still not at the end of the processing.
139
        // Push out the remaining data.
139
        // Push out the remaining data.
140
        m_client.didReceiveDataFromMultipart(SharedBuffer::create(m_buffer.data(), m_buffer.size()));
140
        m_client.didReceiveDataFromMultipart(SharedBuffer::create(WTFMove(m_buffer)));
141
        m_state = State::End;
141
        m_state = State::End;
142
    }
142
    }
143
143
- a/Source/WebCore/platform/network/curl/CurlMultipartHandle.h -2 / +2 lines
Lines 34-40 namespace WebCore { a/Source/WebCore/platform/network/curl/CurlMultipartHandle.h_sec1
34
34
35
class CurlMultipartHandleClient;
35
class CurlMultipartHandleClient;
36
class CurlResponse;
36
class CurlResponse;
37
class SharedBuffer;
37
class FragmentedSharedBuffer;
38
38
39
class CurlMultipartHandle {
39
class CurlMultipartHandle {
40
    WTF_MAKE_FAST_ALLOCATED;
40
    WTF_MAKE_FAST_ALLOCATED;
Lines 44-50 public: a/Source/WebCore/platform/network/curl/CurlMultipartHandle.h_sec2
44
    CurlMultipartHandle(CurlMultipartHandleClient&, const String&);
44
    CurlMultipartHandle(CurlMultipartHandleClient&, const String&);
45
    ~CurlMultipartHandle() { }
45
    ~CurlMultipartHandle() { }
46
46
47
    void didReceiveData(const SharedBuffer&);
47
    void didReceiveData(const FragmentedSharedBuffer&);
48
    void didComplete();
48
    void didComplete();
49
49
50
private:
50
private:
- a/Source/WebCore/platform/network/curl/CurlMultipartHandleClient.h -2 / +2 lines
Lines 28-39 a/Source/WebCore/platform/network/curl/CurlMultipartHandleClient.h_sec1
28
namespace WebCore {
28
namespace WebCore {
29
29
30
class CurlResponse;
30
class CurlResponse;
31
class SharedBuffer;
31
class FragmentedSharedBuffer;
32
32
33
class CurlMultipartHandleClient {
33
class CurlMultipartHandleClient {
34
public:
34
public:
35
    virtual void didReceiveHeaderFromMultipart(const Vector<String>&) = 0;
35
    virtual void didReceiveHeaderFromMultipart(const Vector<String>&) = 0;
36
    virtual void didReceiveDataFromMultipart(Ref<SharedBuffer>&&) = 0;
36
    virtual void didReceiveDataFromMultipart(Ref<FragmentedSharedBuffer>&&) = 0;
37
37
38
protected:
38
protected:
39
    ~CurlMultipartHandleClient() { }
39
    ~CurlMultipartHandleClient() { }
- a/Source/WebCore/platform/network/curl/CurlRequest.cpp -4 / +4 lines
Lines 396-402 size_t CurlRequest::didReceiveHeader(String&& header) a/Source/WebCore/platform/network/curl/CurlRequest.cpp_sec1
396
396
397
// called with data after all headers have been processed via headerCallback
397
// called with data after all headers have been processed via headerCallback
398
398
399
size_t CurlRequest::didReceiveData(Ref<SharedBuffer>&& buffer)
399
size_t CurlRequest::didReceiveData(Ref<FragmentedSharedBuffer>&& buffer)
400
{
400
{
401
    if (isCompletedOrCancelled())
401
    if (isCompletedOrCancelled())
402
        return 0;
402
        return 0;
Lines 444-450 void CurlRequest::didReceiveHeaderFromMultipart(const Vector<String>& headers) a/Source/WebCore/platform/network/curl/CurlRequest.cpp_sec2
444
    invokeDidReceiveResponse(response, Action::None);
444
    invokeDidReceiveResponse(response, Action::None);
445
}
445
}
446
446
447
void CurlRequest::didReceiveDataFromMultipart(Ref<SharedBuffer>&& buffer)
447
void CurlRequest::didReceiveDataFromMultipart(Ref<FragmentedSharedBuffer>&& buffer)
448
{
448
{
449
    if (isCompletedOrCancelled())
449
    if (isCompletedOrCancelled())
450
        return;
450
        return;
Lines 777-783 const String& CurlRequest::getDownloadedFilePath() a/Source/WebCore/platform/network/curl/CurlRequest.cpp_sec3
777
    return m_downloadFilePath;
777
    return m_downloadFilePath;
778
}
778
}
779
779
780
void CurlRequest::writeDataToDownloadFileIfEnabled(const SharedBuffer& buffer)
780
void CurlRequest::writeDataToDownloadFileIfEnabled(const FragmentedSharedBuffer& buffer)
781
{
781
{
782
    {
782
    {
783
        Locker locker { m_downloadMutex };
783
        Locker locker { m_downloadMutex };
Lines 790-796 void CurlRequest::writeDataToDownloadFileIfEnabled(const SharedBuffer& buffer) a/Source/WebCore/platform/network/curl/CurlRequest.cpp_sec4
790
    }
790
    }
791
791
792
    if (m_downloadFileHandle != FileSystem::invalidPlatformFileHandle)
792
    if (m_downloadFileHandle != FileSystem::invalidPlatformFileHandle)
793
        FileSystem::writeToFile(m_downloadFileHandle, buffer.data(), buffer.size());
793
        FileSystem::writeToFile(m_downloadFileHandle, buffer.makeContiguous()->data(), buffer.size());
794
}
794
}
795
795
796
void CurlRequest::closeDownloadFile()
796
void CurlRequest::closeDownloadFile()
- a/Source/WebCore/platform/network/curl/CurlRequest.h -4 / +4 lines
Lines 42-48 namespace WebCore { a/Source/WebCore/platform/network/curl/CurlRequest.h_sec1
42
class CurlRequestClient;
42
class CurlRequestClient;
43
class NetworkLoadMetrics;
43
class NetworkLoadMetrics;
44
class ResourceError;
44
class ResourceError;
45
class SharedBuffer;
45
class FragmentedSharedBuffer;
46
class SynchronousLoaderMessageQueue;
46
class SynchronousLoaderMessageQueue;
47
47
48
class CurlRequest : public ThreadSafeRefCounted<CurlRequest>, public CurlRequestSchedulerClient, public CurlMultipartHandleClient {
48
class CurlRequest : public ThreadSafeRefCounted<CurlRequest>, public CurlRequestSchedulerClient, public CurlMultipartHandleClient {
Lines 122-130 private: a/Source/WebCore/platform/network/curl/CurlRequest.h_sec2
122
    CURL* setupTransfer() override;
122
    CURL* setupTransfer() override;
123
    size_t willSendData(char*, size_t, size_t);
123
    size_t willSendData(char*, size_t, size_t);
124
    size_t didReceiveHeader(String&&);
124
    size_t didReceiveHeader(String&&);
125
    size_t didReceiveData(Ref<SharedBuffer>&&);
125
    size_t didReceiveData(Ref<FragmentedSharedBuffer>&&);
126
    void didReceiveHeaderFromMultipart(const Vector<String>&) override;
126
    void didReceiveHeaderFromMultipart(const Vector<String>&) override;
127
    void didReceiveDataFromMultipart(Ref<SharedBuffer>&&) override;
127
    void didReceiveDataFromMultipart(Ref<FragmentedSharedBuffer>&&) override;
128
    void didCompleteTransfer(CURLcode) override;
128
    void didCompleteTransfer(CURLcode) override;
129
    void didCancelTransfer() override;
129
    void didCancelTransfer() override;
130
    void finalizeTransfer();
130
    void finalizeTransfer();
Lines 153-159 private: a/Source/WebCore/platform/network/curl/CurlRequest.h_sec3
153
    NetworkLoadMetrics networkLoadMetrics();
153
    NetworkLoadMetrics networkLoadMetrics();
154
154
155
    // Download
155
    // Download
156
    void writeDataToDownloadFileIfEnabled(const SharedBuffer&);
156
    void writeDataToDownloadFileIfEnabled(const FragmentedSharedBuffer&);
157
    void closeDownloadFile();
157
    void closeDownloadFile();
158
    void cleanupDownloadFile();
158
    void cleanupDownloadFile();
159
159
- a/Source/WebCore/platform/network/curl/CurlRequestClient.h -2 / +2 lines
Lines 34-40 class CurlRequest; a/Source/WebCore/platform/network/curl/CurlRequestClient.h_sec1
34
class CurlResponse;
34
class CurlResponse;
35
class NetworkLoadMetrics;
35
class NetworkLoadMetrics;
36
class ResourceError;
36
class ResourceError;
37
class SharedBuffer;
37
class FragmentedSharedBuffer;
38
38
39
class CurlRequestClient {
39
class CurlRequestClient {
40
public:
40
public:
Lines 43-49 public: a/Source/WebCore/platform/network/curl/CurlRequestClient.h_sec2
43
43
44
    virtual void curlDidSendData(CurlRequest&, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) = 0;
44
    virtual void curlDidSendData(CurlRequest&, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) = 0;
45
    virtual void curlDidReceiveResponse(CurlRequest&, CurlResponse&&) = 0;
45
    virtual void curlDidReceiveResponse(CurlRequest&, CurlResponse&&) = 0;
46
    virtual void curlDidReceiveBuffer(CurlRequest&, Ref<SharedBuffer>&&) = 0;
46
    virtual void curlDidReceiveBuffer(CurlRequest&, Ref<FragmentedSharedBuffer>&&) = 0;
47
    virtual void curlDidComplete(CurlRequest&, NetworkLoadMetrics&&) = 0;
47
    virtual void curlDidComplete(CurlRequest&, NetworkLoadMetrics&&) = 0;
48
    virtual void curlDidFailWithError(CurlRequest&, ResourceError&&, CertificateInfo&&) = 0;
48
    virtual void curlDidFailWithError(CurlRequest&, ResourceError&&, CertificateInfo&&) = 0;
49
};
49
};
- a/Source/WebCore/platform/network/curl/CurlResourceHandleDelegate.cpp -3 / +4 lines
Lines 142-156 void CurlResourceHandleDelegate::curlDidReceiveResponse(CurlRequest& request, Cu a/Source/WebCore/platform/network/curl/CurlResourceHandleDelegate.cpp_sec1
142
    });
142
    });
143
}
143
}
144
144
145
void CurlResourceHandleDelegate::curlDidReceiveBuffer(CurlRequest&, Ref<SharedBuffer>&& buffer)
145
void CurlResourceHandleDelegate::curlDidReceiveBuffer(CurlRequest&, Ref<FragmentedSharedBuffer>&& buffer)
146
{
146
{
147
    ASSERT(isMainThread());
147
    ASSERT(isMainThread());
148
148
149
    if (cancelledOrClientless())
149
    if (cancelledOrClientless())
150
        return;
150
        return;
151
151
152
    CurlCacheManager::singleton().didReceiveData(m_handle, buffer->data(), buffer->size());
152
    auto contiguousBuffer = buffer->makeContiguous();
153
    client()->didReceiveBuffer(&m_handle, WTFMove(buffer), buffer->size());
153
    CurlCacheManager::singleton().didReceiveData(m_handle, contiguousBuffer->data(), buffer->size());
154
    client()->didReceiveBuffer(&m_handle, WTFMove(contiguousBuffer), buffer->size());
154
}
155
}
155
156
156
void CurlResourceHandleDelegate::curlDidComplete(CurlRequest&, NetworkLoadMetrics&& metrics)
157
void CurlResourceHandleDelegate::curlDidComplete(CurlRequest&, NetworkLoadMetrics&& metrics)
- a/Source/WebCore/platform/network/curl/CurlResourceHandleDelegate.h -1 / +1 lines
Lines 53-59 public: a/Source/WebCore/platform/network/curl/CurlResourceHandleDelegate.h_sec1
53
53
54
    void curlDidSendData(CurlRequest&, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) final;
54
    void curlDidSendData(CurlRequest&, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) final;
55
    void curlDidReceiveResponse(CurlRequest&, CurlResponse&&) final;
55
    void curlDidReceiveResponse(CurlRequest&, CurlResponse&&) final;
56
    void curlDidReceiveBuffer(CurlRequest&, Ref<SharedBuffer>&&) final;
56
    void curlDidReceiveBuffer(CurlRequest&, Ref<FragmentedSharedBuffer>&&) final;
57
    void curlDidComplete(CurlRequest&, NetworkLoadMetrics&&) final;
57
    void curlDidComplete(CurlRequest&, NetworkLoadMetrics&&) final;
58
    void curlDidFailWithError(CurlRequest&, ResourceError&&, CertificateInfo&&) final;
58
    void curlDidFailWithError(CurlRequest&, ResourceError&&, CertificateInfo&&) final;
59
59
- a/Source/WebCore/platform/network/ios/LegacyPreviewLoaderClient.h -2 / +2 lines
Lines 31-42 a/Source/WebCore/platform/network/ios/LegacyPreviewLoaderClient.h_sec1
31
31
32
namespace WebCore {
32
namespace WebCore {
33
33
34
class SharedBuffer;
34
class FragmentedSharedBuffer;
35
35
36
class LegacyPreviewLoaderClient : public RefCounted<LegacyPreviewLoaderClient> {
36
class LegacyPreviewLoaderClient : public RefCounted<LegacyPreviewLoaderClient> {
37
public:
37
public:
38
    virtual ~LegacyPreviewLoaderClient() = default;
38
    virtual ~LegacyPreviewLoaderClient() = default;
39
    virtual void didReceiveBuffer(const SharedBuffer&) { }
39
    virtual void didReceiveBuffer(const FragmentedSharedBuffer&) { }
40
    virtual void didFinishLoading() { }
40
    virtual void didFinishLoading() { }
41
    virtual void didFail() { }
41
    virtual void didFail() { }
42
    virtual bool supportsPasswordEntry() const { return false; }
42
    virtual bool supportsPasswordEntry() const { return false; }
- a/Source/WebCore/platform/win/PasteboardWin.cpp -8 / +8 lines
Lines 356-362 String Pasteboard::readStringInCustomData(const String& type) a/Source/WebCore/platform/win/PasteboardWin.cpp_sec1
356
356
357
struct PasteboardFileCounter final : PasteboardFileReader {
357
struct PasteboardFileCounter final : PasteboardFileReader {
358
    void readFilename(const String&) final { ++count; }
358
    void readFilename(const String&) final { ++count; }
359
    void readBuffer(const String&, const String&, Ref<SharedBuffer>&&) final { ++count; }
359
    void readBuffer(const String&, const String&, Ref<FragmentedSharedBuffer>&&) final { ++count; }
360
360
361
    unsigned count { 0 };
361
    unsigned count { 0 };
362
};
362
};
Lines 974-980 static HGLOBAL createGlobalImageFileDescriptor(const String& url, const String& a/Source/WebCore/platform/win/PasteboardWin.cpp_sec2
974
    return memObj;
974
    return memObj;
975
}
975
}
976
976
977
static HGLOBAL createGlobalImageFileContent(SharedBuffer* data)
977
static HGLOBAL createGlobalImageFileContent(FragmentedSharedBuffer* data)
978
{
978
{
979
    HGLOBAL memObj = GlobalAlloc(GPTR, data->size());
979
    HGLOBAL memObj = GlobalAlloc(GPTR, data->size());
980
    if (!memObj) 
980
    if (!memObj) 
Lines 986-1000 static HGLOBAL createGlobalImageFileContent(SharedBuffer* data) a/Source/WebCore/platform/win/PasteboardWin.cpp_sec3
986
        return 0;
986
        return 0;
987
    }
987
    }
988
988
989
    if (data->data())
989
    if (data->size())
990
        CopyMemory(fileContents, data->data(), data->size());
990
        CopyMemory(fileContents, data->makeContiguous()->data(), data->size());
991
991
992
    GlobalUnlock(memObj);
992
    GlobalUnlock(memObj);
993
993
994
    return memObj;
994
    return memObj;
995
}
995
}
996
996
997
static HGLOBAL createGlobalHDropContent(const URL& url, String& fileName, SharedBuffer* data)
997
static HGLOBAL createGlobalHDropContent(const URL& url, String& fileName, FragmentedSharedBuffer* data)
998
{
998
{
999
    if (fileName.isEmpty() || !data)
999
    if (fileName.isEmpty() || !data)
1000
        return 0;
1000
        return 0;
Lines 1038-1045 static HGLOBAL createGlobalHDropContent(const URL& url, String& fileName, Shared a/Source/WebCore/platform/win/PasteboardWin.cpp_sec4
1038
        // Write the data to this temp file.
1038
        // Write the data to this temp file.
1039
        DWORD written;
1039
        DWORD written;
1040
        BOOL tempWriteSucceeded = FALSE;
1040
        BOOL tempWriteSucceeded = FALSE;
1041
        if (data->data())
1041
        if (data->size())
1042
            tempWriteSucceeded = WriteFile(tempFileHandle, data->data(), data->size(), &written, 0);
1042
            tempWriteSucceeded = WriteFile(tempFileHandle, data->makeContiguous()->data(), data->size(), &written, 0);
1043
        CloseHandle(tempFileHandle);
1043
        CloseHandle(tempFileHandle);
1044
        if (!tempWriteSucceeded)
1044
        if (!tempWriteSucceeded)
1045
            return 0;
1045
            return 0;
Lines 1071-1077 void Pasteboard::writeImageToDataObject(Element& element, const URL& url) a/Source/WebCore/platform/win/PasteboardWin.cpp_sec5
1071
    if (!cachedImage || !cachedImage->imageForRenderer(element.renderer()) || !cachedImage->isLoaded())
1071
    if (!cachedImage || !cachedImage->imageForRenderer(element.renderer()) || !cachedImage->isLoaded())
1072
        return;
1072
        return;
1073
1073
1074
    SharedBuffer* imageBuffer = cachedImage->imageForRenderer(element.renderer())->data();
1074
    FragmentedSharedBuffer* imageBuffer = cachedImage->imageForRenderer(element.renderer())->data();
1075
    if (!imageBuffer || !imageBuffer->size())
1075
    if (!imageBuffer || !imageBuffer->size())
1076
        return;
1076
        return;
1077
1077
- a/Source/WebCore/testing/MockCDMFactory.cpp -12 / +13 lines
Lines 63-69 bool MockCDMFactory::supportsKeySystem(const String& keySystem) a/Source/WebCore/testing/MockCDMFactory.cpp_sec1
63
    return equalIgnoringASCIICase(keySystem, "org.webkit.mock");
63
    return equalIgnoringASCIICase(keySystem, "org.webkit.mock");
64
}
64
}
65
65
66
void MockCDMFactory::addKeysToSessionWithID(const String& id, Vector<Ref<SharedBuffer>>&& keys)
66
void MockCDMFactory::addKeysToSessionWithID(const String& id, Vector<Ref<FragmentedSharedBuffer>>&& keys)
67
{
67
{
68
    auto addResult = m_sessions.add(id, WTFMove(keys));
68
    auto addResult = m_sessions.add(id, WTFMove(keys));
69
    if (addResult.isNewEntry)
69
    if (addResult.isNewEntry)
Lines 74-80 void MockCDMFactory::addKeysToSessionWithID(const String& id, Vector<Ref<SharedB a/Source/WebCore/testing/MockCDMFactory.cpp_sec2
74
        value.append(WTFMove(key));
74
        value.append(WTFMove(key));
75
}
75
}
76
76
77
Vector<Ref<SharedBuffer>> MockCDMFactory::removeKeysFromSessionWithID(const String& id)
77
Vector<Ref<FragmentedSharedBuffer>> MockCDMFactory::removeKeysFromSessionWithID(const String& id)
78
{
78
{
79
    auto it = m_sessions.find(id);
79
    auto it = m_sessions.find(id);
80
    if (it == m_sessions.end())
80
    if (it == m_sessions.end())
Lines 83-89 Vector<Ref<SharedBuffer>> MockCDMFactory::removeKeysFromSessionWithID(const Stri a/Source/WebCore/testing/MockCDMFactory.cpp_sec3
83
    return WTFMove(it->value);
83
    return WTFMove(it->value);
84
}
84
}
85
85
86
const Vector<Ref<SharedBuffer>>* MockCDMFactory::keysForSessionWithID(const String& id) const
86
const Vector<Ref<FragmentedSharedBuffer>>* MockCDMFactory::keysForSessionWithID(const String& id) const
87
{
87
{
88
    auto it = m_sessions.find(id);
88
    auto it = m_sessions.find(id);
89
    if (it == m_sessions.end())
89
    if (it == m_sessions.end())
Lines 202-208 bool MockCDM::supportsSessions() const a/Source/WebCore/testing/MockCDMFactory.cpp_sec4
202
    return m_factory && m_factory->supportsSessions();
202
    return m_factory && m_factory->supportsSessions();
203
}
203
}
204
204
205
bool MockCDM::supportsInitData(const AtomString& initDataType, const SharedBuffer& initData) const
205
bool MockCDM::supportsInitData(const AtomString& initDataType, const FragmentedSharedBuffer& initData) const
206
{
206
{
207
    if (!supportedInitDataTypes().contains(initDataType))
207
    if (!supportedInitDataTypes().contains(initDataType))
208
        return false;
208
        return false;
Lines 211-222 bool MockCDM::supportsInitData(const AtomString& initDataType, const SharedBuffe a/Source/WebCore/testing/MockCDMFactory.cpp_sec5
211
    return true;
211
    return true;
212
}
212
}
213
213
214
RefPtr<SharedBuffer> MockCDM::sanitizeResponse(const SharedBuffer& response) const
214
RefPtr<FragmentedSharedBuffer> MockCDM::sanitizeResponse(const FragmentedSharedBuffer& response) const
215
{
215
{
216
    if (!charactersAreAllASCII(response.data(), response.size()))
216
    auto buffer = response.makeContiguous();
217
    if (!charactersAreAllASCII(buffer->data(), response.size()))
217
        return nullptr;
218
        return nullptr;
218
219
219
    Vector<String> responseArray = String(response.data(), response.size()).split(' ');
220
    Vector<String> responseArray = String(buffer->data(), response.size()).split(' ');
220
221
221
    if (!responseArray.contains(String("valid-response"_s)))
222
    if (!responseArray.contains(String("valid-response"_s)))
222
        return nullptr;
223
        return nullptr;
Lines 269-277 void MockCDMInstance::initializeWithConfiguration(const MediaKeySystemConfigurat a/Source/WebCore/testing/MockCDMFactory.cpp_sec6
269
    callback(initialize());
270
    callback(initialize());
270
}
271
}
271
272
272
void MockCDMInstance::setServerCertificate(Ref<SharedBuffer>&& certificate, SuccessCallback&& callback)
273
void MockCDMInstance::setServerCertificate(Ref<FragmentedSharedBuffer>&& certificate, SuccessCallback&& callback)
273
{
274
{
274
    StringView certificateStringView(certificate->data(), certificate->size());
275
    StringView certificateStringView(certificate->makeContiguous()->data(), certificate->size());
275
276
276
    callback(equalIgnoringASCIICase(certificateStringView, "valid") ? Succeeded : Failed);
277
    callback(equalIgnoringASCIICase(certificateStringView, "valid") ? Succeeded : Failed);
277
}
278
}
Lines 297-303 MockCDMInstanceSession::MockCDMInstanceSession(WeakPtr<MockCDMInstance>&& instan a/Source/WebCore/testing/MockCDMFactory.cpp_sec7
297
{
298
{
298
}
299
}
299
300
300
void MockCDMInstanceSession::requestLicense(LicenseType licenseType, const AtomString& initDataType, Ref<SharedBuffer>&& initData, LicenseCallback&& callback)
301
void MockCDMInstanceSession::requestLicense(LicenseType licenseType, const AtomString& initDataType, Ref<FragmentedSharedBuffer>&& initData, LicenseCallback&& callback)
301
{
302
{
302
    MockCDMFactory* factory = m_instance ? m_instance->factory() : nullptr;
303
    MockCDMFactory* factory = m_instance ? m_instance->factory() : nullptr;
303
    if (!factory) {
304
    if (!factory) {
Lines 323-329 void MockCDMInstanceSession::requestLicense(LicenseType licenseType, const AtomS a/Source/WebCore/testing/MockCDMFactory.cpp_sec8
323
    callback(SharedBuffer::create(license.data(), license.length()), sessionID, false, SuccessValue::Succeeded);
324
    callback(SharedBuffer::create(license.data(), license.length()), sessionID, false, SuccessValue::Succeeded);
324
}
325
}
325
326
326
void MockCDMInstanceSession::updateLicense(const String& sessionID, LicenseType, Ref<SharedBuffer>&& response, LicenseUpdateCallback&& callback)
327
void MockCDMInstanceSession::updateLicense(const String& sessionID, LicenseType, Ref<FragmentedSharedBuffer>&& response, LicenseUpdateCallback&& callback)
327
{
328
{
328
    MockCDMFactory* factory = m_instance ? m_instance->factory() : nullptr;
329
    MockCDMFactory* factory = m_instance ? m_instance->factory() : nullptr;
329
    if (!factory) {
330
    if (!factory) {
Lines 331-337 void MockCDMInstanceSession::updateLicense(const String& sessionID, LicenseType, a/Source/WebCore/testing/MockCDMFactory.cpp_sec9
331
        return;
332
        return;
332
    }
333
    }
333
334
334
    Vector<String> responseVector = String(response->data(), response->size()).split(' ');
335
    Vector<String> responseVector = String(response->makeContiguous()->data(), response->size()).split(' ');
335
336
336
    if (responseVector.contains(String("invalid-format"_s))) {
337
    if (responseVector.contains(String("invalid-format"_s))) {
337
        callback(false, std::nullopt, std::nullopt, std::nullopt, SuccessValue::Failed);
338
        callback(false, std::nullopt, std::nullopt, std::nullopt, SuccessValue::Failed);
- a/Source/WebCore/testing/MockCDMFactory.h -9 / +9 lines
Lines 77-85 public: a/Source/WebCore/testing/MockCDMFactory.h_sec1
77
77
78
    bool hasSessionWithID(const String& id) { return m_sessions.contains(id); }
78
    bool hasSessionWithID(const String& id) { return m_sessions.contains(id); }
79
    void removeSessionWithID(const String& id) { m_sessions.remove(id); }
79
    void removeSessionWithID(const String& id) { m_sessions.remove(id); }
80
    void addKeysToSessionWithID(const String& id, Vector<Ref<SharedBuffer>>&&);
80
    void addKeysToSessionWithID(const String& id, Vector<Ref<FragmentedSharedBuffer>>&&);
81
    const Vector<Ref<SharedBuffer>>* keysForSessionWithID(const String& id) const;
81
    const Vector<Ref<FragmentedSharedBuffer>>* keysForSessionWithID(const String& id) const;
82
    Vector<Ref<SharedBuffer>> removeKeysFromSessionWithID(const String& id);
82
    Vector<Ref<FragmentedSharedBuffer>> removeKeysFromSessionWithID(const String& id);
83
83
84
private:
84
private:
85
    MockCDMFactory();
85
    MockCDMFactory();
Lines 96-102 private: a/Source/WebCore/testing/MockCDMFactory.h_sec2
96
    bool m_canCreateInstances { true };
96
    bool m_canCreateInstances { true };
97
    bool m_supportsServerCertificates { true };
97
    bool m_supportsServerCertificates { true };
98
    bool m_supportsSessions { true };
98
    bool m_supportsSessions { true };
99
    HashMap<String, Vector<Ref<SharedBuffer>>> m_sessions;
99
    HashMap<String, Vector<Ref<FragmentedSharedBuffer>>> m_sessions;
100
};
100
};
101
101
102
class MockCDM : public CDMPrivate {
102
class MockCDM : public CDMPrivate {
Lines 121-128 private: a/Source/WebCore/testing/MockCDMFactory.h_sec3
121
    void loadAndInitialize() final;
121
    void loadAndInitialize() final;
122
    bool supportsServerCertificates() const final;
122
    bool supportsServerCertificates() const final;
123
    bool supportsSessions() const final;
123
    bool supportsSessions() const final;
124
    bool supportsInitData(const AtomString&, const SharedBuffer&) const final;
124
    bool supportsInitData(const AtomString&, const FragmentedSharedBuffer&) const final;
125
    RefPtr<SharedBuffer> sanitizeResponse(const SharedBuffer&) const final;
125
    RefPtr<FragmentedSharedBuffer> sanitizeResponse(const FragmentedSharedBuffer&) const final;
126
    std::optional<String> sanitizeSessionId(const String&) const final;
126
    std::optional<String> sanitizeSessionId(const String&) const final;
127
127
128
    WeakPtr<MockCDMFactory> m_factory;
128
    WeakPtr<MockCDMFactory> m_factory;
Lines 139-145 public: a/Source/WebCore/testing/MockCDMFactory.h_sec4
139
private:
139
private:
140
    ImplementationType implementationType() const final { return ImplementationType::Mock; }
140
    ImplementationType implementationType() const final { return ImplementationType::Mock; }
141
    void initializeWithConfiguration(const MediaKeySystemConfiguration&, AllowDistinctiveIdentifiers, AllowPersistentState, SuccessCallback&&) final;
141
    void initializeWithConfiguration(const MediaKeySystemConfiguration&, AllowDistinctiveIdentifiers, AllowPersistentState, SuccessCallback&&) final;
142
    void setServerCertificate(Ref<SharedBuffer>&&, SuccessCallback&&) final;
142
    void setServerCertificate(Ref<FragmentedSharedBuffer>&&, SuccessCallback&&) final;
143
    void setStorageDirectory(const String&) final;
143
    void setStorageDirectory(const String&) final;
144
    const String& keySystem() const final;
144
    const String& keySystem() const final;
145
    RefPtr<CDMInstanceSession> createSession() final;
145
    RefPtr<CDMInstanceSession> createSession() final;
Lines 154-161 public: a/Source/WebCore/testing/MockCDMFactory.h_sec5
154
    MockCDMInstanceSession(WeakPtr<MockCDMInstance>&&);
154
    MockCDMInstanceSession(WeakPtr<MockCDMInstance>&&);
155
155
156
private:
156
private:
157
    void requestLicense(LicenseType, const AtomString& initDataType, Ref<SharedBuffer>&& initData, LicenseCallback&&) final;
157
    void requestLicense(LicenseType, const AtomString& initDataType, Ref<FragmentedSharedBuffer>&& initData, LicenseCallback&&) final;
158
    void updateLicense(const String&, LicenseType, Ref<SharedBuffer>&&, LicenseUpdateCallback&&) final;
158
    void updateLicense(const String&, LicenseType, Ref<FragmentedSharedBuffer>&&, LicenseUpdateCallback&&) final;
159
    void loadSession(LicenseType, const String&, const String&, LoadSessionCallback&&) final;
159
    void loadSession(LicenseType, const String&, const String&, LoadSessionCallback&&) final;
160
    void closeSession(const String&, CloseSessionCallback&&) final;
160
    void closeSession(const String&, CloseSessionCallback&&) final;
161
    void removeSessionData(const String&, LicenseType, RemoveSessionDataCallback&&) final;
161
    void removeSessionData(const String&, LicenseType, RemoveSessionDataCallback&&) final;
- a/Source/WebCore/testing/MockContentFilter.cpp -1 / +1 lines
Lines 110-116 void MockContentFilter::finishedAddingData() a/Source/WebCore/testing/MockContentFilter.cpp_sec1
110
    maybeDetermineStatus(DecisionPoint::AfterFinishedAddingData);
110
    maybeDetermineStatus(DecisionPoint::AfterFinishedAddingData);
111
}
111
}
112
112
113
Ref<SharedBuffer> MockContentFilter::replacementData() const
113
Ref<FragmentedSharedBuffer> MockContentFilter::replacementData() const
114
{
114
{
115
    ASSERT(didBlockData());
115
    ASSERT(didBlockData());
116
    return SharedBuffer::create(m_replacementData.data(), m_replacementData.size());
116
    return SharedBuffer::create(m_replacementData.data(), m_replacementData.size());
- a/Source/WebCore/testing/MockContentFilter.h -1 / +1 lines
Lines 42-48 public: a/Source/WebCore/testing/MockContentFilter.h_sec1
42
    void responseReceived(const ResourceResponse&) override;
42
    void responseReceived(const ResourceResponse&) override;
43
    void addData(const uint8_t* data, int length) override;
43
    void addData(const uint8_t* data, int length) override;
44
    void finishedAddingData() override;
44
    void finishedAddingData() override;
45
    Ref<SharedBuffer> replacementData() const override;
45
    Ref<FragmentedSharedBuffer> replacementData() const override;
46
#if ENABLE(CONTENT_FILTERING)
46
#if ENABLE(CONTENT_FILTERING)
47
    ContentFilterUnblockHandler unblockHandler() const override;
47
    ContentFilterUnblockHandler unblockHandler() const override;
48
#endif
48
#endif
- a/Source/WebCore/workers/ScriptBuffer.cpp -7 / +4 lines
Lines 38-44 namespace WebCore { a/Source/WebCore/workers/ScriptBuffer.cpp_sec1
38
ScriptBuffer::ScriptBuffer(const String& string)
38
ScriptBuffer::ScriptBuffer(const String& string)
39
{
39
{
40
    auto utf8 = string.utf8();
40
    auto utf8 = string.utf8();
41
    m_buffer = SharedBuffer::create(utf8.data(), utf8.length());
41
    m_buffer.append(utf8.data(), utf8.length());
42
}
42
}
43
43
44
ScriptBuffer ScriptBuffer::empty()
44
ScriptBuffer ScriptBuffer::empty()
Lines 46-59 ScriptBuffer ScriptBuffer::empty() a/Source/WebCore/workers/ScriptBuffer.cpp_sec2
46
    return ScriptBuffer { SharedBuffer::create() };
46
    return ScriptBuffer { SharedBuffer::create() };
47
}
47
}
48
48
49
50
String ScriptBuffer::toString() const
49
String ScriptBuffer::toString() const
51
{
50
{
52
    if (!m_buffer)
51
    if (!m_buffer)
53
        return String();
52
        return String();
54
53
55
    StringBuilder builder;
54
    StringBuilder builder;
56
    m_buffer->forEachSegment([&](auto& segment) {
55
    m_buffer.get()->forEachSegment([&](auto& segment) {
57
        builder.append(String::fromUTF8(segment.data(), segment.size()));
56
        builder.append(String::fromUTF8(segment.data(), segment.size()));
58
    });
57
    });
59
    return builder.toString();
58
    return builder.toString();
Lines 61-75 String ScriptBuffer::toString() const a/Source/WebCore/workers/ScriptBuffer.cpp_sec3
61
60
62
bool ScriptBuffer::containsSingleFileMappedSegment() const
61
bool ScriptBuffer::containsSingleFileMappedSegment() const
63
{
62
{
64
    return m_buffer && m_buffer->hasOneSegment() && m_buffer->begin()->segment->containsMappedFileData();
63
    return m_buffer && m_buffer.get()->hasOneSegment() && m_buffer.get()->begin()->segment->containsMappedFileData();
65
}
64
}
66
65
67
void ScriptBuffer::append(const String& string)
66
void ScriptBuffer::append(const String& string)
68
{
67
{
69
    if (!m_buffer)
70
        m_buffer = SharedBuffer::create();
71
    auto utf8 = string.utf8();
68
    auto utf8 = string.utf8();
72
    m_buffer->append(utf8.data(), utf8.length());
69
    m_buffer.append(utf8.data(), utf8.length());
73
}
70
}
74
71
75
bool operator==(const ScriptBuffer& a, const ScriptBuffer& b)
72
bool operator==(const ScriptBuffer& a, const ScriptBuffer& b)
- a/Source/WebCore/workers/ScriptBuffer.h -5 / +5 lines
Lines 38-44 class ScriptBuffer { a/Source/WebCore/workers/ScriptBuffer.h_sec1
38
public:
38
public:
39
    ScriptBuffer() = default;
39
    ScriptBuffer() = default;
40
40
41
    ScriptBuffer(RefPtr<SharedBuffer>&& buffer)
41
    ScriptBuffer(RefPtr<FragmentedSharedBuffer>&& buffer)
42
        : m_buffer(WTFMove(buffer))
42
        : m_buffer(WTFMove(buffer))
43
    {
43
    {
44
    }
44
    }
Lines 48-64 public: a/Source/WebCore/workers/ScriptBuffer.h_sec2
48
    WEBCORE_EXPORT explicit ScriptBuffer(const String&);
48
    WEBCORE_EXPORT explicit ScriptBuffer(const String&);
49
49
50
    String toString() const;
50
    String toString() const;
51
    SharedBuffer* buffer() const { return m_buffer.get(); }
51
    const FragmentedSharedBuffer* buffer() const { return m_buffer.get().get(); }
52
52
53
    ScriptBuffer isolatedCopy() const { return ScriptBuffer(m_buffer ? RefPtr<SharedBuffer>(m_buffer->copy()) : nullptr); }
53
    ScriptBuffer isolatedCopy() const { return ScriptBuffer(m_buffer ? RefPtr<FragmentedSharedBuffer>(m_buffer.copy()) : nullptr); }
54
    explicit operator bool() const { return !!m_buffer; }
54
    explicit operator bool() const { return !!m_buffer; }
55
    bool isEmpty() const { return !m_buffer || !m_buffer->size(); }
55
    bool isEmpty() const { return m_buffer.isEmpty(); }
56
56
57
    WEBCORE_EXPORT bool containsSingleFileMappedSegment() const;
57
    WEBCORE_EXPORT bool containsSingleFileMappedSegment() const;
58
    void append(const String&);
58
    void append(const String&);
59
59
60
private:
60
private:
61
    RefPtr<SharedBuffer> m_buffer; // Contains the UTF-8 encoded script.
61
    SharedBufferBuilder m_buffer; // Contains the UTF-8 encoded script.
62
};
62
};
63
63
64
bool operator==(const ScriptBuffer&, const ScriptBuffer&);
64
bool operator==(const ScriptBuffer&, const ScriptBuffer&);
- a/Source/WebCore/workers/WorkerFontLoadRequest.cpp -6 / +13 lines
Lines 44-49 namespace WebCore { a/Source/WebCore/workers/WorkerFontLoadRequest.cpp_sec1
44
WorkerFontLoadRequest::WorkerFontLoadRequest(URL&& url, LoadedFromOpaqueSource loadedFromOpaqueSource)
44
WorkerFontLoadRequest::WorkerFontLoadRequest(URL&& url, LoadedFromOpaqueSource loadedFromOpaqueSource)
45
    : m_url(WTFMove(url))
45
    : m_url(WTFMove(url))
46
    , m_loadedFromOpaqueSource(loadedFromOpaqueSource)
46
    , m_loadedFromOpaqueSource(loadedFromOpaqueSource)
47
    , m_data(makeUniqueRef<SharedBufferBuilder>())
47
{
48
{
48
}
49
}
49
50
Lines 75-86 void WorkerFontLoadRequest::load(WorkerGlobalScope& workerGlobalScope) a/Source/WebCore/workers/WorkerFontLoadRequest.cpp_sec2
75
    WorkerThreadableLoader::loadResourceSynchronously(workerGlobalScope, WTFMove(request), *this, options);
76
    WorkerThreadableLoader::loadResourceSynchronously(workerGlobalScope, WTFMove(request), *this, options);
76
}
77
}
77
78
79
bool WorkerFontLoadRequest::isPending() const
80
{
81
    return !m_isLoading && !m_errorOccurred && m_data->isNull();
82
}
83
78
bool WorkerFontLoadRequest::ensureCustomFontData(const AtomString&)
84
bool WorkerFontLoadRequest::ensureCustomFontData(const AtomString&)
79
{
85
{
80
    if (!m_fontCustomPlatformData && !m_errorOccurred && !m_isLoading) {
86
    if (!m_fontCustomPlatformData && !m_errorOccurred && !m_isLoading) {
81
        convertWOFFToSfntIfNecessary(m_data);
87
        RefPtr<SharedBuffer> contiguousData;
82
        if (m_data) {
88
        if (m_data->get())
83
            m_fontCustomPlatformData = createFontCustomPlatformData(*m_data, m_url.fragmentIdentifier().toString());
89
            contiguousData = m_data->take()->makeContiguous();
90
        convertWOFFToSfntIfNecessary(contiguousData);
91
        if (contiguousData) {
92
            m_data->append(*contiguousData);
93
            m_fontCustomPlatformData = createFontCustomPlatformData(*contiguousData, m_url.fragmentIdentifier().toString());
84
            if (!m_fontCustomPlatformData)
94
            if (!m_fontCustomPlatformData)
85
                m_errorOccurred = true;
95
                m_errorOccurred = true;
86
        }
96
        }
Lines 117-125 void WorkerFontLoadRequest::didReceiveData(const uint8_t* data, int dataLength) a/Source/WebCore/workers/WorkerFontLoadRequest.cpp_sec3
117
    if (m_errorOccurred)
127
    if (m_errorOccurred)
118
        return;
128
        return;
119
129
120
    if (!m_data)
121
        m_data = SharedBuffer::create();
122
123
    m_data->append(data, dataLength);
130
    m_data->append(data, dataLength);
124
}
131
}
125
132
- a/Source/WebCore/workers/WorkerFontLoadRequest.h -3 / +4 lines
Lines 30-42 a/Source/WebCore/workers/WorkerFontLoadRequest.h_sec1
30
#include "ResourceLoaderOptions.h"
30
#include "ResourceLoaderOptions.h"
31
#include "ThreadableLoaderClient.h"
31
#include "ThreadableLoaderClient.h"
32
#include <wtf/URL.h>
32
#include <wtf/URL.h>
33
#include <wtf/UniqueRef.h>
33
#include <wtf/WeakPtr.h>
34
#include <wtf/WeakPtr.h>
34
35
35
namespace WebCore {
36
namespace WebCore {
36
37
37
class FontCreationContext;
38
class FontCreationContext;
38
class ScriptExecutionContext;
39
class ScriptExecutionContext;
39
class SharedBuffer;
40
class SharedBufferBuilder;
40
class WorkerGlobalScope;
41
class WorkerGlobalScope;
41
42
42
struct FontCustomPlatformData;
43
struct FontCustomPlatformData;
Lines 51-57 public: a/Source/WebCore/workers/WorkerFontLoadRequest.h_sec2
51
52
52
private:
53
private:
53
    const URL& url() const final { return m_url; }
54
    const URL& url() const final { return m_url; }
54
    bool isPending() const final { return !m_isLoading && !m_errorOccurred && !m_data; }
55
    bool isPending() const final;
55
    bool isLoading() const final { return m_isLoading; }
56
    bool isLoading() const final { return m_isLoading; }
56
    bool errorOccurred() const final { return m_errorOccurred; }
57
    bool errorOccurred() const final { return m_errorOccurred; }
57
58
Lines 76-82 private: a/Source/WebCore/workers/WorkerFontLoadRequest.h_sec3
76
    FontLoadRequestClient* m_fontLoadRequestClient { nullptr };
77
    FontLoadRequestClient* m_fontLoadRequestClient { nullptr };
77
78
78
    WeakPtr<ScriptExecutionContext> m_context;
79
    WeakPtr<ScriptExecutionContext> m_context;
79
    RefPtr<SharedBuffer> m_data;
80
    UniqueRef<SharedBufferBuilder> m_data;
80
    std::unique_ptr<FontCustomPlatformData> m_fontCustomPlatformData;
81
    std::unique_ptr<FontCustomPlatformData> m_fontCustomPlatformData;
81
};
82
};
82
83
- a/Source/WebCore/workers/service/context/ServiceWorkerFetch.h -2 / +2 lines
Lines 42-48 class ResourceRequest; a/Source/WebCore/workers/service/context/ServiceWorkerFetch.h_sec1
42
class ResourceResponse;
42
class ResourceResponse;
43
class ServiceWorkerGlobalScope;
43
class ServiceWorkerGlobalScope;
44
class ServiceWorkerGlobalScope;
44
class ServiceWorkerGlobalScope;
45
class SharedBuffer;
45
class FragmentedSharedBuffer;
46
46
47
namespace ServiceWorkerFetch {
47
namespace ServiceWorkerFetch {
48
class Client : public ThreadSafeRefCounted<Client, WTF::DestructionThread::Main> {
48
class Client : public ThreadSafeRefCounted<Client, WTF::DestructionThread::Main> {
Lines 51-57 public: a/Source/WebCore/workers/service/context/ServiceWorkerFetch.h_sec2
51
51
52
    virtual void didReceiveRedirection(const ResourceResponse&) = 0;
52
    virtual void didReceiveRedirection(const ResourceResponse&) = 0;
53
    virtual void didReceiveResponse(const ResourceResponse&) = 0;
53
    virtual void didReceiveResponse(const ResourceResponse&) = 0;
54
    virtual void didReceiveData(Ref<SharedBuffer>&&) = 0;
54
    virtual void didReceiveData(Ref<FragmentedSharedBuffer>&&) = 0;
55
    virtual void didReceiveFormDataAndFinish(Ref<FormData>&&) = 0;
55
    virtual void didReceiveFormDataAndFinish(Ref<FormData>&&) = 0;
56
    virtual void didFail(const ResourceError&) = 0;
56
    virtual void didFail(const ResourceError&) = 0;
57
    virtual void didFinish() = 0;
57
    virtual void didFinish() = 0;
- a/Source/WebCore/workers/service/server/SWScriptStorage.cpp -1 / +2 lines
Lines 127-133 ScriptBuffer SWScriptStorage::retrieve(const ServiceWorkerRegistrationKey& regis a/Source/WebCore/workers/service/server/SWScriptStorage.cpp_sec1
127
    }
127
    }
128
128
129
    // FIXME: Do we need to disable file mapping in more cases to avoid having too many file descriptors open?
129
    // FIXME: Do we need to disable file mapping in more cases to avoid having too many file descriptors open?
130
    return SharedBuffer::createWithContentsOfFile(scriptPath, FileSystem::MappedFileMode::Private, shouldUseFileMapping(*fileSize) ? SharedBuffer::MayUseFileMapping::Yes : SharedBuffer::MayUseFileMapping::No);
130
    RefPtr<FragmentedSharedBuffer> buffer = SharedBuffer::createWithContentsOfFile(scriptPath, FileSystem::MappedFileMode::Private, shouldUseFileMapping(*fileSize) ? SharedBuffer::MayUseFileMapping::Yes : SharedBuffer::MayUseFileMapping::No);
131
    return buffer;
131
}
132
}
132
133
133
void SWScriptStorage::clear(const ServiceWorkerRegistrationKey& registrationKey)
134
void SWScriptStorage::clear(const ServiceWorkerRegistrationKey& registrationKey)
- a/Source/WebCore/xml/XMLHttpRequest.cpp -7 / +5 lines
Lines 118-123 XMLHttpRequest::XMLHttpRequest(ScriptExecutionContext& context) a/Source/WebCore/xml/XMLHttpRequest.cpp_sec1
118
    , m_responseCacheIsValid(false)
118
    , m_responseCacheIsValid(false)
119
    , m_readyState(static_cast<unsigned>(UNSENT))
119
    , m_readyState(static_cast<unsigned>(UNSENT))
120
    , m_responseType(static_cast<unsigned>(ResponseType::EmptyString))
120
    , m_responseType(static_cast<unsigned>(ResponseType::EmptyString))
121
    , m_binaryResponseBuilder(makeUniqueRef<SharedBufferBuilder>())
121
    , m_progressEventThrottle(*this)
122
    , m_progressEventThrottle(*this)
122
    , m_timeoutTimer(*this, &XMLHttpRequest::timeoutTimerFired)
123
    , m_timeoutTimer(*this, &XMLHttpRequest::timeoutTimerFired)
123
{
124
{
Lines 207-214 Ref<Blob> XMLHttpRequest::createResponseBlob() a/Source/WebCore/xml/XMLHttpRequest.cpp_sec2
207
208
208
    // FIXME: We just received the data from NetworkProcess, and are sending it back. This is inefficient.
209
    // FIXME: We just received the data from NetworkProcess, and are sending it back. This is inefficient.
209
    Vector<uint8_t> data;
210
    Vector<uint8_t> data;
210
    if (m_binaryResponseBuilder)
211
    if (!m_binaryResponseBuilder->isNull())
211
        data = std::exchange(m_binaryResponseBuilder, nullptr)->extractData();
212
        data = m_binaryResponseBuilder->take()->extractData();
212
    String normalizedContentType = Blob::normalizedContentType(responseMIMEType(FinalMIMEType::Yes)); // responseMIMEType defaults to text/xml which may be incorrect.
213
    String normalizedContentType = Blob::normalizedContentType(responseMIMEType(FinalMIMEType::Yes)); // responseMIMEType defaults to text/xml which may be incorrect.
213
    return Blob::create(scriptExecutionContext(), WTFMove(data), normalizedContentType);
214
    return Blob::create(scriptExecutionContext(), WTFMove(data), normalizedContentType);
214
}
215
}
Lines 218-225 RefPtr<ArrayBuffer> XMLHttpRequest::createResponseArrayBuffer() a/Source/WebCore/xml/XMLHttpRequest.cpp_sec3
218
    ASSERT(responseType() == ResponseType::Arraybuffer);
219
    ASSERT(responseType() == ResponseType::Arraybuffer);
219
    ASSERT(doneWithoutErrors());
220
    ASSERT(doneWithoutErrors());
220
221
221
    auto result = m_binaryResponseBuilder ? m_binaryResponseBuilder->tryCreateArrayBuffer() : ArrayBuffer::create(nullptr, 0);
222
    auto result = !m_binaryResponseBuilder->isNull() ? m_binaryResponseBuilder->take()->tryCreateArrayBuffer() : ArrayBuffer::create(nullptr, 0);
222
    m_binaryResponseBuilder = nullptr;
223
    return result;
223
    return result;
224
}
224
}
225
225
Lines 741-747 void XMLHttpRequest::clearResponseBuffers() a/Source/WebCore/xml/XMLHttpRequest.cpp_sec4
741
    m_responseEncoding = String();
741
    m_responseEncoding = String();
742
    m_createdDocument = false;
742
    m_createdDocument = false;
743
    m_responseDocument = nullptr;
743
    m_responseDocument = nullptr;
744
    m_binaryResponseBuilder = nullptr;
744
    m_binaryResponseBuilder->reset();
745
    m_responseCacheIsValid = false;
745
    m_responseCacheIsValid = false;
746
}
746
}
747
747
Lines 1065-1072 void XMLHttpRequest::didReceiveData(const uint8_t* data, int len) a/Source/WebCore/xml/XMLHttpRequest.cpp_sec5
1065
        m_responseBuilder.append(m_decoder->decode(data, len));
1065
        m_responseBuilder.append(m_decoder->decode(data, len));
1066
    else {
1066
    else {
1067
        // Buffer binary data.
1067
        // Buffer binary data.
1068
        if (!m_binaryResponseBuilder)
1069
            m_binaryResponseBuilder = SharedBuffer::create();
1070
        m_binaryResponseBuilder->append(data, len);
1068
        m_binaryResponseBuilder->append(data, len);
1071
    }
1069
    }
1072
1070
- a/Source/WebCore/xml/XMLHttpRequest.h -2 / +3 lines
Lines 29-34 a/Source/WebCore/xml/XMLHttpRequest.h_sec1
29
#include "ThreadableLoaderClient.h"
29
#include "ThreadableLoaderClient.h"
30
#include "UserGestureIndicator.h"
30
#include "UserGestureIndicator.h"
31
#include <wtf/URL.h>
31
#include <wtf/URL.h>
32
#include <wtf/UniqueRef.h>
32
#include "XMLHttpRequestEventTarget.h"
33
#include "XMLHttpRequestEventTarget.h"
33
#include "XMLHttpRequestProgressEventThrottle.h"
34
#include "XMLHttpRequestProgressEventThrottle.h"
34
#include <variant>
35
#include <variant>
Lines 45-51 class Blob; a/Source/WebCore/xml/XMLHttpRequest.h_sec2
45
class Document;
46
class Document;
46
class DOMFormData;
47
class DOMFormData;
47
class SecurityOrigin;
48
class SecurityOrigin;
48
class SharedBuffer;
49
class SharedBufferBuilder;
49
class TextResourceDecoder;
50
class TextResourceDecoder;
50
class ThreadableLoader;
51
class ThreadableLoader;
51
class URLSearchParams;
52
class URLSearchParams;
Lines 237-243 private: a/Source/WebCore/xml/XMLHttpRequest.h_sec3
237
238
238
    RefPtr<Document> m_responseDocument;
239
    RefPtr<Document> m_responseDocument;
239
240
240
    RefPtr<SharedBuffer> m_binaryResponseBuilder;
241
    UniqueRef<SharedBufferBuilder> m_binaryResponseBuilder;
241
242
242
    StringBuilder m_responseBuilder;
243
    StringBuilder m_responseBuilder;
243
244
- a/Source/WebKit/ChangeLog +329 lines
Lines 1-3 a/Source/WebKit/ChangeLog_sec1
1
2021-12-05  Jean-Yves Avenard  <jya@apple.com>
2
3
        SourceBufferParser should be using contiguous shared buffer
4
        https://bugs.webkit.org/show_bug.cgi?id=233865
5
        rdar://problem/86085253
6
7
        Reviewed by NOBODY (OOPS!).
8
9
        * WebProcess/GPU/media/SourceBufferPrivateRemote.cpp:
10
        (WebKit::SourceBufferPrivateRemote::append):
11
        * WebProcess/GPU/media/SourceBufferPrivateRemote.h:
12
13
2021-12-03  Jean-Yves Avenard  <jya@apple.com>
14
15
        Rename SharedBuffer classes.
16
        https://bugs.webkit.org/show_bug.cgi?id=233677
17
        rdar://problem/85963900
18
19
        Reviewed by NOBODY (OOPS!).
20
21
        SharedBuffer are renamed FragmentedSharedBuffer and
22
        ContiguousSharedBuffer to SharedBuffer to better reflect their actual
23
        types.
24
25
        * GPUProcess/media/RemoteCDMInstanceProxy.cpp:
26
        * GPUProcess/media/RemoteCDMInstanceProxy.h:
27
        * GPUProcess/media/RemoteCDMInstanceSessionProxy.cpp:
28
        * GPUProcess/media/RemoteCDMInstanceSessionProxy.h:
29
        * GPUProcess/media/RemoteCDMProxy.cpp:
30
        * GPUProcess/media/RemoteCDMProxy.h:
31
        * GPUProcess/media/RemoteLegacyCDMProxy.h:
32
        * GPUProcess/media/RemoteLegacyCDMSessionProxy.cpp:
33
        * GPUProcess/media/RemoteLegacyCDMSessionProxy.h:
34
        * GPUProcess/media/RemoteMediaResource.cpp:
35
        * GPUProcess/media/RemoteMediaResource.h:
36
        * GPUProcess/webrtc/RemoteMediaRecorder.cpp:
37
        * NetworkProcess/Downloads/PendingDownload.h:
38
        * NetworkProcess/NetworkCORSPreflightChecker.cpp:
39
        * NetworkProcess/NetworkCORSPreflightChecker.h:
40
        * NetworkProcess/NetworkDataTask.h:
41
        * NetworkProcess/NetworkLoad.cpp:
42
        * NetworkProcess/NetworkLoad.h:
43
        * NetworkProcess/NetworkLoadClient.h:
44
        * NetworkProcess/NetworkResourceLoader.cpp:
45
        * NetworkProcess/NetworkResourceLoader.h:
46
        * NetworkProcess/PingLoad.cpp:
47
        * NetworkProcess/PingLoad.h:
48
        * NetworkProcess/PreconnectTask.cpp:
49
        * NetworkProcess/PreconnectTask.h:
50
        * NetworkProcess/ServiceWorker/ServiceWorkerNavigationPreloader.cpp:
51
        * NetworkProcess/ServiceWorker/ServiceWorkerNavigationPreloader.h:
52
        * NetworkProcess/ServiceWorker/ServiceWorkerSoftUpdateLoader.cpp:
53
        * NetworkProcess/ServiceWorker/ServiceWorkerSoftUpdateLoader.h:
54
        * NetworkProcess/cache/CacheStorageEngineCache.cpp:
55
        * NetworkProcess/cache/NetworkCache.cpp:
56
        * NetworkProcess/cache/NetworkCache.h:
57
        * NetworkProcess/cache/NetworkCacheEntry.cpp:
58
        * NetworkProcess/cache/NetworkCacheEntry.h:
59
        * NetworkProcess/cache/NetworkCacheSpeculativeLoad.cpp:
60
        * NetworkProcess/cache/NetworkCacheSpeculativeLoad.h:
61
        * NetworkProcess/cache/PrefetchCache.cpp:
62
        * NetworkProcess/cache/PrefetchCache.h:
63
        * NetworkProcess/cocoa/NetworkDataTaskCocoa.h:
64
        * NetworkProcess/cocoa/NetworkDataTaskCocoa.mm:
65
        * NetworkProcess/curl/NetworkDataTaskCurl.cpp:
66
        * NetworkProcess/curl/NetworkDataTaskCurl.h:
67
        * NetworkProcess/soup/NetworkDataTaskSoup.cpp:
68
        * NetworkProcess/webrtc/NetworkRTCProvider.h:
69
        * Platform/IPC/SharedBufferCopy.cpp:
70
        * Platform/IPC/SharedBufferCopy.h:
71
        * Platform/IPC/SharedBufferDataReference.h:
72
        * Platform/SharedMemory.cpp:
73
        * Platform/SharedMemory.h:
74
        * Shared/Cocoa/WebCoreArgumentCodersCocoa.mm:
75
        * Shared/RemoteLayerTree/CGDisplayListImageBufferBackend.cpp:
76
        * Shared/ShareableResource.cpp:
77
        * Shared/ShareableResource.h:
78
        * Shared/WebCoreArgumentCoders.cpp:
79
        * Shared/WebCoreArgumentCoders.h:
80
        * Shared/WebHitTestResultData.cpp:
81
        * Shared/gtk/ArgumentCodersGtk.cpp:
82
        * Shared/win/WebCoreArgumentCodersWin.cpp:
83
        * UIProcess/API/APIAttachment.cpp:
84
        * UIProcess/API/APIAttachment.h:
85
        * UIProcess/API/APIContentRuleListStore.cpp:
86
        * UIProcess/API/APIContentRuleListStore.h:
87
        * UIProcess/API/APINavigationClient.h:
88
        * UIProcess/API/Cocoa/APIAttachmentCocoa.mm:
89
        * UIProcess/API/gtk/DropTargetGtk3.cpp:
90
        * UIProcess/Cocoa/NavigationState.h:
91
        * UIProcess/Cocoa/NavigationState.mm:
92
        * UIProcess/Cocoa/WebProcessProxyCocoa.mm:
93
        * UIProcess/Cocoa/WebViewImpl.h:
94
        * UIProcess/Cocoa/WebViewImpl.mm:
95
        * UIProcess/PageClient.h:
96
        * UIProcess/WebPageProxy.h:
97
        * UIProcess/WebURLSchemeTask.cpp:
98
        * UIProcess/WebURLSchemeTask.h:
99
        * UIProcess/gtk/Clipboard.h:
100
        * UIProcess/gtk/ClipboardGtk3.cpp:
101
        * UIProcess/gtk/ClipboardGtk4.cpp:
102
        * UIProcess/ios/PageClientImplIOS.h:
103
        * UIProcess/ios/PageClientImplIOS.mm:
104
        * UIProcess/ios/WKContentViewInteraction.mm:
105
        * UIProcess/ios/WebPageProxyIOS.mm:
106
        * UIProcess/mac/PageClientImplMac.h:
107
        * UIProcess/mac/PageClientImplMac.mm:
108
        * UIProcess/mac/WebPageProxyMac.mm:
109
        * WebProcess/GPU/media/RemoteCDM.cpp:
110
        * WebProcess/GPU/media/RemoteCDM.h:
111
        * WebProcess/GPU/media/RemoteCDMInstance.cpp:
112
        * WebProcess/GPU/media/RemoteCDMInstance.h:
113
        * WebProcess/GPU/media/RemoteCDMInstanceSession.cpp:
114
        * WebProcess/GPU/media/RemoteCDMInstanceSession.h:
115
        * WebProcess/GPU/media/RemoteImageDecoderAVF.cpp:
116
        * WebProcess/GPU/media/RemoteImageDecoderAVF.h:
117
        * WebProcess/GPU/media/RemoteImageDecoderAVFManager.cpp:
118
        * WebProcess/GPU/media/RemoteImageDecoderAVFManager.h:
119
        * WebProcess/GPU/media/RemoteLegacyCDMSession.cpp:
120
        * WebProcess/GPU/media/SourceBufferPrivateRemote.cpp:
121
        * WebProcess/GPU/media/SourceBufferPrivateRemote.h:
122
        * WebProcess/GPU/webrtc/MediaRecorderPrivate.cpp:
123
        * WebProcess/GPU/webrtc/MediaRecorderPrivate.h:
124
        * WebProcess/InjectedBundle/API/APIInjectedBundleEditorClient.h:
125
        * WebProcess/InjectedBundle/API/APIInjectedBundlePageLoaderClient.h:
126
        * WebProcess/InjectedBundle/API/mac/WKWebProcessPlugInBrowserContextController.mm:
127
        * WebProcess/InjectedBundle/InjectedBundlePageEditorClient.cpp:
128
        * WebProcess/InjectedBundle/InjectedBundlePageEditorClient.h:
129
        * WebProcess/InjectedBundle/InjectedBundlePageLoaderClient.cpp:
130
        * WebProcess/InjectedBundle/InjectedBundlePageLoaderClient.h:
131
        * WebProcess/Network/NetworkProcessConnection.cpp:
132
        * WebProcess/Network/WebResourceLoader.cpp:
133
        * WebProcess/Plugins/PDF/PDFPlugin.h:
134
        * WebProcess/Plugins/PDF/PDFPlugin.mm:
135
        * WebProcess/Plugins/Plugin.h:
136
        * WebProcess/Plugins/PluginView.cpp:
137
        * WebProcess/Plugins/PluginView.h:
138
        * WebProcess/Storage/WebServiceWorkerFetchTaskClient.cpp:
139
        * WebProcess/Storage/WebServiceWorkerFetchTaskClient.h:
140
        * WebProcess/WebCoreSupport/WebEditorClient.cpp:
141
        * WebProcess/WebCoreSupport/WebEditorClient.h:
142
        * WebProcess/WebCoreSupport/WebFrameLoaderClient.cpp:
143
        * WebProcess/WebCoreSupport/WebPlatformStrategies.cpp:
144
        * WebProcess/WebCoreSupport/WebPlatformStrategies.h:
145
        * WebProcess/WebCoreSupport/ios/WebPreviewLoaderClient.cpp:
146
        * WebProcess/WebCoreSupport/ios/WebPreviewLoaderClient.h:
147
        * WebProcess/WebCoreSupport/mac/WebDragClientMac.mm:
148
        * WebProcess/WebPage/WebFrame.cpp:
149
        * WebProcess/WebPage/WebPage.cpp:
150
        * WebProcess/WebPage/WebPage.h:
151
        * WebProcess/WebPage/ios/WebPageIOS.mm:
152
        * WebProcess/WebPage/mac/WebPageMac.mm:
153
        * WebProcess/win/WebProcessWin.cpp:
154
155
2021-11-28  Jean-Yves Avenard  <jya@apple.com>
156
157
        Add SharedBufferBuilder class
158
        https://bugs.webkit.org/show_bug.cgi?id=233442
159
        rdar://85693939
160
161
        Reviewed by NOBODY (OOPS!).
162
163
        * NetworkProcess/NetworkResourceLoader.cpp:
164
        (WebKit::NetworkResourceLoader::startNetworkLoad):
165
        (WebKit::NetworkResourceLoader::didReceiveResponse):
166
        (WebKit::NetworkResourceLoader::didReceiveBuffer):
167
        (WebKit::NetworkResourceLoader::didFinishLoading):
168
        (WebKit::NetworkResourceLoader::bufferingTimerFired):
169
        (WebKit::NetworkResourceLoader::tryStoreAsCacheEntry):
170
        * NetworkProcess/NetworkResourceLoader.h:
171
        * NetworkProcess/cache/NetworkCacheSpeculativeLoad.cpp:
172
        (WebKit::NetworkCache::SpeculativeLoad::SpeculativeLoad):
173
        (WebKit::NetworkCache::SpeculativeLoad::didReceiveResponse):
174
        (WebKit::NetworkCache::SpeculativeLoad::didReceiveBuffer):
175
        (WebKit::NetworkCache::SpeculativeLoad::didFinishLoading):
176
        * NetworkProcess/cache/NetworkCacheSpeculativeLoad.h:
177
        * UIProcess/WebURLSchemeTask.cpp:
178
        (WebKit::WebURLSchemeTask::WebURLSchemeTask):
179
        (WebKit::WebURLSchemeTask::didReceiveData):
180
        (WebKit::WebURLSchemeTask::didComplete):
181
        * UIProcess/WebURLSchemeTask.h:
182
        * WebProcess/Plugins/PluginView.cpp:
183
        (WebKit::PluginView::PluginView):
184
        (WebKit::PluginView::manualLoadDidReceiveData):
185
        (WebKit::PluginView::manualLoadDidFail):
186
        (WebKit::PluginView::liveResourceData const):
187
        (WebKit::PluginView::redeliverManualStream):
188
        * WebProcess/Plugins/PluginView.h:
189
        * WebProcess/Storage/WebServiceWorkerFetchTaskClient.cpp:
190
        (WebKit::WebServiceWorkerFetchTaskClient::didReceiveData):
191
        (WebKit::WebServiceWorkerFetchTaskClient::continueDidReceiveResponse):
192
        * WebProcess/Storage/WebServiceWorkerFetchTaskClient.h:
193
        * WebProcess/WebCoreSupport/ios/WebPreviewLoaderClient.cpp:
194
        (WebKit::WebPreviewLoaderClient::didFinishLoading):
195
        (WebKit::WebPreviewLoaderClient::didFail):
196
        * WebProcess/WebCoreSupport/ios/WebPreviewLoaderClient.h:
197
198
2021-11-25  Jean-Yves Avenard  <jya@apple.com>
199
200
        Distinguish contiguous SharedBuffer from non-contiguous one and guarantee immutability
201
        https://bugs.webkit.org/show_bug.cgi?id=233030
202
        rdar://85333814
203
204
        Reviewed by Darin Adler.
205
206
        * GPUProcess/webrtc/RemoteMediaRecorder.cpp:
207
        (WebKit::RemoteMediaRecorder::fetchData):
208
        * NetworkProcess/NetworkResourceLoader.cpp:
209
        (WebKit::sendReplyToSynchronousRequest):
210
        * NetworkProcess/ServiceWorker/ServiceWorkerSoftUpdateLoader.cpp:
211
        (WebKit::ServiceWorkerSoftUpdateLoader::didReceiveBuffer):
212
        * NetworkProcess/cache/CacheStorageEngineCache.cpp:
213
        (WebKit::CacheStorage::Cache::encode):
214
        (WebKit::CacheStorage::Cache::decode):
215
        * NetworkProcess/cache/NetworkCacheEntry.cpp:
216
        (WebKit::NetworkCache::Entry::encodeAsStorageRecord const):
217
        * NetworkProcess/soup/NetworkDataTaskSoup.cpp:
218
        (WebKit::NetworkDataTaskSoup::didReadDataURL):
219
        * Platform/IPC/SharedBufferCopy.cpp:
220
        (IPC::SharedBufferCopy::decode):
221
        * Platform/IPC/SharedBufferCopy.h:
222
        (IPC::SharedBufferCopy::SharedBufferCopy):
223
        (IPC::SharedBufferCopy::buffer):
224
        (IPC::SharedBufferCopy::buffer const):
225
        * Platform/SharedMemory.cpp:
226
        (WebKit::SharedMemory::createSharedBuffer const):
227
        * Platform/SharedMemory.h:
228
        * Shared/APIWebArchiveResource.mm:
229
        (API::WebArchiveResource::data):
230
        * Shared/Cocoa/WebCoreArgumentCodersCocoa.mm:
231
        (IPC::ArgumentCoder<Ref<WebCore::Font>>::decodePlatformData):
232
        * Shared/RemoteLayerTree/CGDisplayListImageBufferBackend.cpp:
233
        (WebKit::CGDisplayListImageBufferBackend::createImageBufferBackendHandle const):
234
        * Shared/ShareableResource.cpp:
235
        (WebKit::ShareableResource::wrapInSharedBuffer):
236
        (WebKit::ShareableResource::Handle::tryWrapInSharedBuffer const):
237
        * Shared/ShareableResource.h:
238
        * Shared/WebCoreArgumentCoders.cpp:
239
        (IPC::decodeSharedBuffer):
240
        (IPC::encodeTypesAndData):
241
        (IPC::decodeTypesAndData):
242
        (IPC::ArgumentCoder<DOMCacheEngine::Record>::encode):
243
        (IPC::ArgumentCoder<DOMCacheEngine::Record>::decode):
244
        (IPC::ArgumentCoder<PasteboardCustomData::Entry>::decode):
245
        (IPC::ArgumentCoder<WebCore::SerializedAttachmentData>::decode):
246
        (IPC::ArgumentCoder<RefPtr<WebCore::SharedBuffer>>::decode):
247
        (IPC::ArgumentCoder<Ref<WebCore::SharedBuffer>>::decode):
248
        (IPC::ArgumentCoder<RefPtr<WebCore::ContiguousSharedBuffer>>::encode):
249
        (IPC::ArgumentCoder<RefPtr<WebCore::ContiguousSharedBuffer>>::decode):
250
        (IPC::ArgumentCoder<Ref<WebCore::ContiguousSharedBuffer>>::encode):
251
        (IPC::ArgumentCoder<Ref<WebCore::ContiguousSharedBuffer>>::decode):
252
        (IPC::ArgumentCoder<WebCore::ScriptBuffer>::decode):
253
        * Shared/WebCoreArgumentCoders.h:
254
        * Shared/gtk/ArgumentCodersGtk.cpp:
255
        (IPC::ArgumentCoder<SelectionData>::decode):
256
        * Shared/win/WebCoreArgumentCodersWin.cpp:
257
        (IPC::ArgumentCoder<Ref<Font>>::decodePlatformData):
258
        * UIProcess/API/APIAttachment.cpp:
259
        (API::Attachment::createSerializedRepresentation const):
260
        (API::Attachment::updateFromSerializedRepresentation):
261
        * UIProcess/API/APIAttachment.h:
262
        * UIProcess/API/APIContentRuleListStore.cpp:
263
        (API::getData):
264
        * UIProcess/API/Cocoa/APIAttachmentCocoa.mm:
265
        (API::Attachment::createSerializedRepresentation const):
266
        (API::Attachment::updateFromSerializedRepresentation):
267
        * UIProcess/API/Cocoa/WKWebView.mm:
268
        (-[WKWebView _storeAppHighlight:]):
269
        * UIProcess/API/gtk/DropTargetGtk3.cpp:
270
        (WebKit::DropTarget::dataReceived):
271
        * UIProcess/Cocoa/NavigationState.mm:
272
        (WebKit::NavigationState::NavigationClient::didFinishLoadForQuickLookDocumentInMainFrame):
273
        * UIProcess/Cocoa/WebViewImpl.mm:
274
        (WebKit::WebViewImpl::writeSelectionToPasteboard):
275
        (WebKit::WebViewImpl::setPromisedDataForImage):
276
        (WebKit::WebViewImpl::provideDataForPasteboard):
277
        (WebKit::WebViewImpl::namesOfPromisedFilesDroppedAtDestination):
278
        (WebKit::WebViewImpl::requestDOMPasteAccess):
279
        * UIProcess/PageClient.h:
280
        * UIProcess/WebPageProxy.h:
281
        * UIProcess/WebURLSchemeTask.cpp:
282
        (WebKit::WebURLSchemeTask::didComplete):
283
        * UIProcess/ios/PageClientImplIOS.h:
284
        * UIProcess/ios/PageClientImplIOS.mm:
285
        (WebKit::PageClientImpl::saveImageToLibrary):
286
        * UIProcess/ios/WKContentViewInteraction.mm:
287
        (-[WKContentView canPerformActionForWebView:withSender:]):
288
        (allPasteboardItemOriginsMatchOrigin):
289
        (-[WKContentView actionSheetAssistant:shareElementWithImage:rect:]):
290
        * UIProcess/ios/WebPageProxyIOS.mm:
291
        (WebKit::WebPageProxy::dataSelectionForPasteboard):
292
        * UIProcess/mac/WebPageProxyMac.mm:
293
        (WebKit::WebPageProxy::dataSelectionForPasteboard):
294
        * WebProcess/InjectedBundle/API/APIInjectedBundleEditorClient.h:
295
        (API::InjectedBundle::EditorClient::getPasteboardDataForRange):
296
        * WebProcess/InjectedBundle/API/mac/WKWebProcessPlugInBrowserContextController.mm:
297
        (-[WKWebProcessPlugInBrowserContextController _setEditingDelegate:]):
298
        * WebProcess/InjectedBundle/InjectedBundlePageEditorClient.cpp:
299
        (WebKit::InjectedBundlePageEditorClient::getPasteboardDataForRange):
300
        * WebProcess/InjectedBundle/InjectedBundlePageEditorClient.h:
301
        * WebProcess/InjectedBundle/InjectedBundlePageLoaderClient.cpp:
302
        (WebKit::releaseSharedBuffer):
303
        (WebKit::InjectedBundlePageLoaderClient::willLoadDataRequest):
304
        * WebProcess/Model/mac/ARKitInlinePreviewModelPlayerMac.mm:
305
        (WebKit::ARKitInlinePreviewModelPlayerMac::createFile):
306
        * WebProcess/Network/NetworkProcessConnection.cpp:
307
        (WebKit::NetworkProcessConnection::didCacheResource):
308
        * WebProcess/Network/WebResourceLoader.cpp:
309
        (WebKit::WebResourceLoader::didReceiveData):
310
        * WebProcess/WebCoreSupport/WebEditorClient.cpp:
311
        (WebKit::WebEditorClient::getClientPasteboardData):
312
        * WebProcess/WebCoreSupport/WebEditorClient.h:
313
        * WebProcess/WebCoreSupport/WebFrameLoaderClient.cpp:
314
        (WebKit::WebFrameLoaderClient::finishedLoading):
315
        * WebProcess/WebCoreSupport/WebPlatformStrategies.cpp:
316
        (WebKit::WebPlatformStrategies::bufferForType):
317
        (WebKit::WebPlatformStrategies::readBufferFromClipboard):
318
        (WebKit::WebPlatformStrategies::readBufferFromPasteboard):
319
        * WebProcess/WebCoreSupport/WebPlatformStrategies.h:
320
        * WebProcess/WebCoreSupport/mac/WebDragClientMac.mm:
321
        (WebKit::WebDragClient::declareAndWriteDragImage):
322
        * WebProcess/WebPage/WebFrame.cpp:
323
        (WebKit::WebFrame::source const):
324
        * WebProcess/WebPage/mac/WebPageMac.mm:
325
        (WebKit::WebPage::getDataSelectionForPasteboard):
326
        * WebProcess/cocoa/VideoFullscreenManager.mm:
327
        (WebKit::VideoFullscreenManager::supportsVideoFullscreen const):
328
        (WebKit::VideoFullscreenManager::supportsVideoFullscreenStandby const):
329
1
2021-12-05  Said Abou-Hallawa  <said@apple.com>
330
2021-12-05  Said Abou-Hallawa  <said@apple.com>
2
331
3
        [GPU Process] Add the encoding/decoding for Filter and FilterEffect
332
        [GPU Process] Add the encoding/decoding for Filter and FilterEffect
- a/Source/WebKit/GPUProcess/media/RemoteCDMInstanceProxy.cpp -1 / +1 lines
Lines 61-67 RemoteCDMInstanceProxy::~RemoteCDMInstanceProxy() a/Source/WebKit/GPUProcess/media/RemoteCDMInstanceProxy.cpp_sec1
61
    m_instance->clearClient();
61
    m_instance->clearClient();
62
}
62
}
63
63
64
void RemoteCDMInstanceProxy::unrequestedInitializationDataReceived(const String& type, Ref<SharedBuffer>&& initData)
64
void RemoteCDMInstanceProxy::unrequestedInitializationDataReceived(const String& type, Ref<FragmentedSharedBuffer>&& initData)
65
{
65
{
66
    if (!m_cdm)
66
    if (!m_cdm)
67
        return;
67
        return;
- a/Source/WebKit/GPUProcess/media/RemoteCDMInstanceProxy.h -1 / +1 lines
Lines 66-72 private: a/Source/WebKit/GPUProcess/media/RemoteCDMInstanceProxy.h_sec1
66
    RemoteCDMInstanceProxy(WeakPtr<RemoteCDMProxy>&&, Ref<WebCore::CDMInstance>&&, UniqueRef<RemoteCDMInstanceConfiguration>&&, RemoteCDMInstanceIdentifier);
66
    RemoteCDMInstanceProxy(WeakPtr<RemoteCDMProxy>&&, Ref<WebCore::CDMInstance>&&, UniqueRef<RemoteCDMInstanceConfiguration>&&, RemoteCDMInstanceIdentifier);
67
67
68
    // CDMInstanceClient
68
    // CDMInstanceClient
69
    void unrequestedInitializationDataReceived(const String&, Ref<WebCore::SharedBuffer>&&) final;
69
    void unrequestedInitializationDataReceived(const String&, Ref<WebCore::FragmentedSharedBuffer>&&) final;
70
70
71
    // IPC::MessageReceiver
71
    // IPC::MessageReceiver
72
    void didReceiveMessage(IPC::Connection&, IPC::Decoder&) final;
72
    void didReceiveMessage(IPC::Connection&, IPC::Decoder&) final;
- a/Source/WebKit/GPUProcess/media/RemoteCDMInstanceSessionProxy.cpp -3 / +3 lines
Lines 70-76 void RemoteCDMInstanceSessionProxy::requestLicense(LicenseType type, AtomString a/Source/WebKit/GPUProcess/media/RemoteCDMInstanceSessionProxy.cpp_sec1
70
        return;
70
        return;
71
    }
71
    }
72
72
73
    m_session->requestLicense(type, initDataType, initData.buffer().releaseNonNull(), [completion = WTFMove(completion)] (Ref<SharedBuffer>&& message, const String& sessionId, bool needsIndividualization, CDMInstanceSession::SuccessValue succeeded) mutable {
73
    m_session->requestLicense(type, initDataType, initData.buffer().releaseNonNull(), [completion = WTFMove(completion)] (Ref<FragmentedSharedBuffer>&& message, const String& sessionId, bool needsIndividualization, CDMInstanceSession::SuccessValue succeeded) mutable {
74
        completion(WTFMove(message), sessionId, needsIndividualization, succeeded == CDMInstanceSession::Succeeded);
74
        completion(WTFMove(message), sessionId, needsIndividualization, succeeded == CDMInstanceSession::Succeeded);
75
    });
75
    });
76
}
76
}
Lines 115-121 void RemoteCDMInstanceSessionProxy::closeSession(const String& sessionId, CloseS a/Source/WebKit/GPUProcess/media/RemoteCDMInstanceSessionProxy.cpp_sec2
115
115
116
void RemoteCDMInstanceSessionProxy::removeSessionData(const String& sessionId, LicenseType type, RemoveSessionDataCallback&& completion)
116
void RemoteCDMInstanceSessionProxy::removeSessionData(const String& sessionId, LicenseType type, RemoveSessionDataCallback&& completion)
117
{
117
{
118
    m_session->removeSessionData(sessionId, type, [completion = WTFMove(completion)] (CDMInstanceSession::KeyStatusVector&& keyStatuses, std::optional<Ref<SharedBuffer>>&& expiredSessionsData, CDMInstanceSession::SuccessValue succeeded) mutable {
118
    m_session->removeSessionData(sessionId, type, [completion = WTFMove(completion)] (CDMInstanceSession::KeyStatusVector&& keyStatuses, std::optional<Ref<FragmentedSharedBuffer>>&& expiredSessionsData, CDMInstanceSession::SuccessValue succeeded) mutable {
119
        std::optional<IPC::SharedBufferCopy> expiredSessionDataReference;
119
        std::optional<IPC::SharedBufferCopy> expiredSessionDataReference;
120
        if (expiredSessionsData)
120
        if (expiredSessionsData)
121
            expiredSessionDataReference = IPC::SharedBufferCopy(WTFMove(*expiredSessionsData));
121
            expiredSessionDataReference = IPC::SharedBufferCopy(WTFMove(*expiredSessionsData));
Lines 149-155 void RemoteCDMInstanceSessionProxy::updateKeyStatuses(KeyStatusVector&& keyStatu a/Source/WebKit/GPUProcess/media/RemoteCDMInstanceSessionProxy.cpp_sec3
149
    gpuConnectionToWebProcess->connection().send(Messages::RemoteCDMInstanceSession::UpdateKeyStatuses(WTFMove(keyStatuses)), m_identifier);
149
    gpuConnectionToWebProcess->connection().send(Messages::RemoteCDMInstanceSession::UpdateKeyStatuses(WTFMove(keyStatuses)), m_identifier);
150
}
150
}
151
151
152
void RemoteCDMInstanceSessionProxy::sendMessage(CDMMessageType type, Ref<SharedBuffer>&& message)
152
void RemoteCDMInstanceSessionProxy::sendMessage(CDMMessageType type, Ref<FragmentedSharedBuffer>&& message)
153
{
153
{
154
    if (!m_cdm)
154
    if (!m_cdm)
155
        return;
155
        return;
- a/Source/WebKit/GPUProcess/media/RemoteCDMInstanceSessionProxy.h -1 / +1 lines
Lines 77-83 private: a/Source/WebKit/GPUProcess/media/RemoteCDMInstanceSessionProxy.h_sec1
77
77
78
    // CDMInstanceSessionClient
78
    // CDMInstanceSessionClient
79
    void updateKeyStatuses(KeyStatusVector&&) final;
79
    void updateKeyStatuses(KeyStatusVector&&) final;
80
    void sendMessage(WebCore::CDMMessageType, Ref<WebCore::SharedBuffer>&& message) final;
80
    void sendMessage(WebCore::CDMMessageType, Ref<WebCore::FragmentedSharedBuffer>&& message) final;
81
    void sessionIdChanged(const String&) final;
81
    void sessionIdChanged(const String&) final;
82
    PlatformDisplayID displayID() final { return m_displayID; }
82
    PlatformDisplayID displayID() final { return m_displayID; }
83
83
- a/Source/WebKit/GPUProcess/media/RemoteCDMProxy.cpp -2 / +2 lines
Lines 63-74 RemoteCDMProxy::RemoteCDMProxy(WeakPtr<RemoteCDMFactoryProxy>&& factory, std::un a/Source/WebKit/GPUProcess/media/RemoteCDMProxy.cpp_sec1
63
63
64
RemoteCDMProxy::~RemoteCDMProxy() = default;
64
RemoteCDMProxy::~RemoteCDMProxy() = default;
65
65
66
bool RemoteCDMProxy::supportsInitData(const AtomString& type, const SharedBuffer& data)
66
bool RemoteCDMProxy::supportsInitData(const AtomString& type, const FragmentedSharedBuffer& data)
67
{
67
{
68
    return m_private->supportsInitData(type, data);
68
    return m_private->supportsInitData(type, data);
69
}
69
}
70
70
71
RefPtr<SharedBuffer> RemoteCDMProxy::sanitizeResponse(const SharedBuffer& response)
71
RefPtr<FragmentedSharedBuffer> RemoteCDMProxy::sanitizeResponse(const FragmentedSharedBuffer& response)
72
{
72
{
73
    return m_private->sanitizeResponse(response);
73
    return m_private->sanitizeResponse(response);
74
}
74
}
- a/Source/WebKit/GPUProcess/media/RemoteCDMProxy.h -3 / +3 lines
Lines 36-42 a/Source/WebKit/GPUProcess/media/RemoteCDMProxy.h_sec1
36
#include <wtf/UniqueRef.h>
36
#include <wtf/UniqueRef.h>
37
37
38
namespace WebCore {
38
namespace WebCore {
39
class SharedBuffer;
39
class FragmentedSharedBuffer;
40
enum class CDMRequirement : uint8_t;
40
enum class CDMRequirement : uint8_t;
41
enum class CDMSessionType : uint8_t;
41
enum class CDMSessionType : uint8_t;
42
struct CDMKeySystemConfiguration;
42
struct CDMKeySystemConfiguration;
Lines 58-65 public: a/Source/WebKit/GPUProcess/media/RemoteCDMProxy.h_sec2
58
58
59
    RemoteCDMFactoryProxy* factory() const { return m_factory.get(); }
59
    RemoteCDMFactoryProxy* factory() const { return m_factory.get(); }
60
60
61
    bool supportsInitData(const AtomString&, const WebCore::SharedBuffer&);
61
    bool supportsInitData(const AtomString&, const WebCore::FragmentedSharedBuffer&);
62
    RefPtr<WebCore::SharedBuffer> sanitizeResponse(const WebCore::SharedBuffer& response);
62
    RefPtr<WebCore::FragmentedSharedBuffer> sanitizeResponse(const WebCore::FragmentedSharedBuffer& response);
63
    std::optional<String> sanitizeSessionId(const String& sessionId);
63
    std::optional<String> sanitizeSessionId(const String& sessionId);
64
64
65
private:
65
private:
- a/Source/WebKit/GPUProcess/media/RemoteLegacyCDMProxy.h -1 / +1 lines
Lines 36-42 a/Source/WebKit/GPUProcess/media/RemoteLegacyCDMProxy.h_sec1
36
#include <wtf/WeakPtr.h>
36
#include <wtf/WeakPtr.h>
37
37
38
namespace WebCore {
38
namespace WebCore {
39
class SharedBuffer;
39
class FragmentedSharedBuffer;
40
}
40
}
41
41
42
namespace WebKit {
42
namespace WebKit {
- a/Source/WebKit/GPUProcess/media/RemoteLegacyCDMSessionProxy.h -1 / +1 lines
Lines 37-43 a/Source/WebKit/GPUProcess/media/RemoteLegacyCDMSessionProxy.h_sec1
37
namespace WebCore {
37
namespace WebCore {
38
class LegacyCDM;
38
class LegacyCDM;
39
class LegacyCDMSession;
39
class LegacyCDMSession;
40
class SharedBuffer;
40
class FragmentedSharedBuffer;
41
}
41
}
42
42
43
namespace IPC {
43
namespace IPC {
- a/Source/WebKit/GPUProcess/media/RemoteMediaResource.cpp -1 / +1 lines
Lines 96-102 void RemoteMediaResource::dataSent(uint64_t bytesSent, uint64_t totalBytesToBeSe a/Source/WebKit/GPUProcess/media/RemoteMediaResource.cpp_sec1
96
        m_client->dataSent(*this, bytesSent, totalBytesToBeSent);
96
        m_client->dataSent(*this, bytesSent, totalBytesToBeSent);
97
}
97
}
98
98
99
void RemoteMediaResource::dataReceived(Ref<SharedBuffer>&& data)
99
void RemoteMediaResource::dataReceived(Ref<FragmentedSharedBuffer>&& data)
100
{
100
{
101
    if (m_client)
101
    if (m_client)
102
        m_client->dataReceived(*this, WTFMove(data));
102
        m_client->dataReceived(*this, WTFMove(data));
- a/Source/WebKit/GPUProcess/media/RemoteMediaResource.h -2 / +2 lines
Lines 34-40 a/Source/WebKit/GPUProcess/media/RemoteMediaResource.h_sec1
34
34
35
namespace WebCore {
35
namespace WebCore {
36
class NetworkLoadMetrics;
36
class NetworkLoadMetrics;
37
class SharedBuffer;
37
class FragmentedSharedBuffer;
38
}
38
}
39
39
40
namespace WebKit {
40
namespace WebKit {
Lines 57-63 public: a/Source/WebKit/GPUProcess/media/RemoteMediaResource.h_sec2
57
    void responseReceived(const WebCore::ResourceResponse&, bool, CompletionHandler<void(WebCore::ShouldContinuePolicyCheck)>&&);
57
    void responseReceived(const WebCore::ResourceResponse&, bool, CompletionHandler<void(WebCore::ShouldContinuePolicyCheck)>&&);
58
    void redirectReceived(WebCore::ResourceRequest&&, const WebCore::ResourceResponse&, CompletionHandler<void(WebCore::ResourceRequest&&)>&&);
58
    void redirectReceived(WebCore::ResourceRequest&&, const WebCore::ResourceResponse&, CompletionHandler<void(WebCore::ResourceRequest&&)>&&);
59
    void dataSent(uint64_t, uint64_t);
59
    void dataSent(uint64_t, uint64_t);
60
    void dataReceived(Ref<WebCore::SharedBuffer>&&);
60
    void dataReceived(Ref<WebCore::FragmentedSharedBuffer>&&);
61
    void accessControlCheckFailed(const WebCore::ResourceError&);
61
    void accessControlCheckFailed(const WebCore::ResourceError&);
62
    void loadFailed(const WebCore::ResourceError&);
62
    void loadFailed(const WebCore::ResourceError&);
63
    void loadFinished(const WebCore::NetworkLoadMetrics&);
63
    void loadFinished(const WebCore::NetworkLoadMetrics&);
- a/Source/WebKit/GPUProcess/webrtc/RemoteMediaRecorder.cpp -1 / +2 lines
Lines 107-113 void RemoteMediaRecorder::videoSampleAvailable(WebCore::RemoteVideoSample&& remo a/Source/WebKit/GPUProcess/webrtc/RemoteMediaRecorder.cpp_sec1
107
void RemoteMediaRecorder::fetchData(CompletionHandler<void(IPC::DataReference&&, double)>&& completionHandler)
107
void RemoteMediaRecorder::fetchData(CompletionHandler<void(IPC::DataReference&&, double)>&& completionHandler)
108
{
108
{
109
    m_writer->fetchData([completionHandler = WTFMove(completionHandler)](auto&& data, auto timeCode) mutable {
109
    m_writer->fetchData([completionHandler = WTFMove(completionHandler)](auto&& data, auto timeCode) mutable {
110
        auto* pointer = data ? data->data() : nullptr;
110
        auto buffer = data ? data->makeContiguous() : RefPtr<WebCore::SharedBuffer>();
111
        auto* pointer = buffer ? buffer->data() : nullptr;
111
        completionHandler(IPC::DataReference { pointer, data ? data->size() : 0 }, timeCode);
112
        completionHandler(IPC::DataReference { pointer, data ? data->size() : 0 }, timeCode);
112
    });
113
    });
113
}
114
}
- a/Source/WebKit/NetworkProcess/Downloads/PendingDownload.h -1 / +1 lines
Lines 68-74 private: a/Source/WebKit/NetworkProcess/Downloads/PendingDownload.h_sec1
68
    bool isAllowedToAskUserForCredentials() const final { return m_isAllowedToAskUserForCredentials; }
68
    bool isAllowedToAskUserForCredentials() const final { return m_isAllowedToAskUserForCredentials; }
69
    void willSendRedirectedRequest(WebCore::ResourceRequest&&, WebCore::ResourceRequest&& redirectRequest, WebCore::ResourceResponse&& redirectResponse) override;
69
    void willSendRedirectedRequest(WebCore::ResourceRequest&&, WebCore::ResourceRequest&& redirectRequest, WebCore::ResourceResponse&& redirectResponse) override;
70
    void didReceiveResponse(WebCore::ResourceResponse&&, ResponseCompletionHandler&&) override;
70
    void didReceiveResponse(WebCore::ResourceResponse&&, ResponseCompletionHandler&&) override;
71
    void didReceiveBuffer(Ref<WebCore::SharedBuffer>&&, int reportedEncodedDataLength) override { };
71
    void didReceiveBuffer(Ref<WebCore::FragmentedSharedBuffer>&&, int reportedEncodedDataLength) override { };
72
    void didFinishLoading(const WebCore::NetworkLoadMetrics&) override { };
72
    void didFinishLoading(const WebCore::NetworkLoadMetrics&) override { };
73
    void didFailLoading(const WebCore::ResourceError&) override;
73
    void didFailLoading(const WebCore::ResourceError&) override;
74
74
- a/Source/WebKit/NetworkProcess/NetworkCORSPreflightChecker.cpp -1 / +1 lines
Lines 119-125 void NetworkCORSPreflightChecker::didReceiveResponse(WebCore::ResourceResponse&& a/Source/WebKit/NetworkProcess/NetworkCORSPreflightChecker.cpp_sec1
119
    completionHandler(PolicyAction::Use);
119
    completionHandler(PolicyAction::Use);
120
}
120
}
121
121
122
void NetworkCORSPreflightChecker::didReceiveData(Ref<WebCore::SharedBuffer>&&)
122
void NetworkCORSPreflightChecker::didReceiveData(Ref<WebCore::FragmentedSharedBuffer>&&)
123
{
123
{
124
    CORS_CHECKER_RELEASE_LOG("didReceiveData");
124
    CORS_CHECKER_RELEASE_LOG("didReceiveData");
125
}
125
}
- a/Source/WebKit/NetworkProcess/NetworkCORSPreflightChecker.h -1 / +1 lines
Lines 71-77 private: a/Source/WebKit/NetworkProcess/NetworkCORSPreflightChecker.h_sec1
71
    void willPerformHTTPRedirection(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&, RedirectCompletionHandler&&) final;
71
    void willPerformHTTPRedirection(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&, RedirectCompletionHandler&&) final;
72
    void didReceiveChallenge(WebCore::AuthenticationChallenge&&, NegotiatedLegacyTLS, ChallengeCompletionHandler&&) final;
72
    void didReceiveChallenge(WebCore::AuthenticationChallenge&&, NegotiatedLegacyTLS, ChallengeCompletionHandler&&) final;
73
    void didReceiveResponse(WebCore::ResourceResponse&&, NegotiatedLegacyTLS, ResponseCompletionHandler&&) final;
73
    void didReceiveResponse(WebCore::ResourceResponse&&, NegotiatedLegacyTLS, ResponseCompletionHandler&&) final;
74
    void didReceiveData(Ref<WebCore::SharedBuffer>&&) final;
74
    void didReceiveData(Ref<WebCore::FragmentedSharedBuffer>&&) final;
75
    void didCompleteWithError(const WebCore::ResourceError&, const WebCore::NetworkLoadMetrics&) final;
75
    void didCompleteWithError(const WebCore::ResourceError&, const WebCore::NetworkLoadMetrics&) final;
76
    void didSendData(uint64_t totalBytesSent, uint64_t totalBytesExpectedToSend) final;
76
    void didSendData(uint64_t totalBytesSent, uint64_t totalBytesExpectedToSend) final;
77
    void wasBlocked() final;
77
    void wasBlocked() final;
- a/Source/WebKit/NetworkProcess/NetworkDataTask.h -2 / +2 lines
Lines 43-49 namespace WebCore { a/Source/WebKit/NetworkProcess/NetworkDataTask.h_sec1
43
class AuthenticationChallenge;
43
class AuthenticationChallenge;
44
class ResourceError;
44
class ResourceError;
45
class ResourceResponse;
45
class ResourceResponse;
46
class SharedBuffer;
46
class FragmentedSharedBuffer;
47
}
47
}
48
48
49
namespace WebKit {
49
namespace WebKit {
Lines 63-69 public: a/Source/WebKit/NetworkProcess/NetworkDataTask.h_sec2
63
    virtual void willPerformHTTPRedirection(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&, RedirectCompletionHandler&&) = 0;
63
    virtual void willPerformHTTPRedirection(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&, RedirectCompletionHandler&&) = 0;
64
    virtual void didReceiveChallenge(WebCore::AuthenticationChallenge&&, NegotiatedLegacyTLS, ChallengeCompletionHandler&&) = 0;
64
    virtual void didReceiveChallenge(WebCore::AuthenticationChallenge&&, NegotiatedLegacyTLS, ChallengeCompletionHandler&&) = 0;
65
    virtual void didReceiveResponse(WebCore::ResourceResponse&&, NegotiatedLegacyTLS, ResponseCompletionHandler&&) = 0;
65
    virtual void didReceiveResponse(WebCore::ResourceResponse&&, NegotiatedLegacyTLS, ResponseCompletionHandler&&) = 0;
66
    virtual void didReceiveData(Ref<WebCore::SharedBuffer>&&) = 0;
66
    virtual void didReceiveData(Ref<WebCore::FragmentedSharedBuffer>&&) = 0;
67
    virtual void didCompleteWithError(const WebCore::ResourceError&, const WebCore::NetworkLoadMetrics&) = 0;
67
    virtual void didCompleteWithError(const WebCore::ResourceError&, const WebCore::NetworkLoadMetrics&) = 0;
68
    virtual void didSendData(uint64_t totalBytesSent, uint64_t totalBytesExpectedToSend) = 0;
68
    virtual void didSendData(uint64_t totalBytesSent, uint64_t totalBytesExpectedToSend) = 0;
69
    virtual void wasBlocked() = 0;
69
    virtual void wasBlocked() = 0;
- a/Source/WebKit/NetworkProcess/NetworkLoad.cpp -1 / +1 lines
Lines 256-262 void NetworkLoad::notifyDidReceiveResponse(ResourceResponse&& response, Negotiat a/Source/WebKit/NetworkProcess/NetworkLoad.cpp_sec1
256
    m_client.get().didReceiveResponse(WTFMove(response), WTFMove(completionHandler));
256
    m_client.get().didReceiveResponse(WTFMove(response), WTFMove(completionHandler));
257
}
257
}
258
258
259
void NetworkLoad::didReceiveData(Ref<SharedBuffer>&& buffer)
259
void NetworkLoad::didReceiveData(Ref<FragmentedSharedBuffer>&& buffer)
260
{
260
{
261
    // FIXME: This should be the encoded data length, not the decoded data length.
261
    // FIXME: This should be the encoded data length, not the decoded data length.
262
    auto size = buffer->size();
262
    auto size = buffer->size();
- a/Source/WebKit/NetworkProcess/NetworkLoad.h -1 / +1 lines
Lines 80-86 private: a/Source/WebKit/NetworkProcess/NetworkLoad.h_sec1
80
    void willPerformHTTPRedirection(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&, RedirectCompletionHandler&&) final;
80
    void willPerformHTTPRedirection(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&, RedirectCompletionHandler&&) final;
81
    void didReceiveChallenge(WebCore::AuthenticationChallenge&&, NegotiatedLegacyTLS, ChallengeCompletionHandler&&) final;
81
    void didReceiveChallenge(WebCore::AuthenticationChallenge&&, NegotiatedLegacyTLS, ChallengeCompletionHandler&&) final;
82
    void didReceiveResponse(WebCore::ResourceResponse&&, NegotiatedLegacyTLS, ResponseCompletionHandler&&) final;
82
    void didReceiveResponse(WebCore::ResourceResponse&&, NegotiatedLegacyTLS, ResponseCompletionHandler&&) final;
83
    void didReceiveData(Ref<WebCore::SharedBuffer>&&) final;
83
    void didReceiveData(Ref<WebCore::FragmentedSharedBuffer>&&) final;
84
    void didCompleteWithError(const WebCore::ResourceError&, const WebCore::NetworkLoadMetrics&) final;
84
    void didCompleteWithError(const WebCore::ResourceError&, const WebCore::NetworkLoadMetrics&) final;
85
    void didSendData(uint64_t totalBytesSent, uint64_t totalBytesExpectedToSend) final;
85
    void didSendData(uint64_t totalBytesSent, uint64_t totalBytesExpectedToSend) final;
86
    void wasBlocked() final;
86
    void wasBlocked() final;
- a/Source/WebKit/NetworkProcess/NetworkLoadClient.h -2 / +2 lines
Lines 32-38 a/Source/WebKit/NetworkProcess/NetworkLoadClient.h_sec1
32
namespace WebCore {
32
namespace WebCore {
33
class AuthenticationChallenge;
33
class AuthenticationChallenge;
34
class NetworkLoadMetrics;
34
class NetworkLoadMetrics;
35
class SharedBuffer;
35
class FragmentedSharedBuffer;
36
enum class PolicyAction : uint8_t;
36
enum class PolicyAction : uint8_t;
37
}
37
}
38
38
Lines 51-57 public: a/Source/WebKit/NetworkProcess/NetworkLoadClient.h_sec2
51
    virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent) = 0;
51
    virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent) = 0;
52
    virtual void willSendRedirectedRequest(WebCore::ResourceRequest&&, WebCore::ResourceRequest&& redirectRequest, WebCore::ResourceResponse&& redirectResponse) = 0;
52
    virtual void willSendRedirectedRequest(WebCore::ResourceRequest&&, WebCore::ResourceRequest&& redirectRequest, WebCore::ResourceResponse&& redirectResponse) = 0;
53
    virtual void didReceiveResponse(WebCore::ResourceResponse&&, ResponseCompletionHandler&&) = 0;
53
    virtual void didReceiveResponse(WebCore::ResourceResponse&&, ResponseCompletionHandler&&) = 0;
54
    virtual void didReceiveBuffer(Ref<WebCore::SharedBuffer>&&, int reportedEncodedDataLength) = 0;
54
    virtual void didReceiveBuffer(Ref<WebCore::FragmentedSharedBuffer>&&, int reportedEncodedDataLength) = 0;
55
    virtual void didFinishLoading(const WebCore::NetworkLoadMetrics&) = 0;
55
    virtual void didFinishLoading(const WebCore::NetworkLoadMetrics&) = 0;
56
    virtual void didFailLoading(const WebCore::ResourceError&) = 0;
56
    virtual void didFailLoading(const WebCore::ResourceError&) = 0;
57
    virtual void didBlockAuthenticationChallenge() { };
57
    virtual void didBlockAuthenticationChallenge() { };
- a/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp -22 / +24 lines
Lines 87-100 struct NetworkResourceLoader::SynchronousLoadData { a/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp_sec1
87
    ResourceError error;
87
    ResourceError error;
88
};
88
};
89
89
90
static void sendReplyToSynchronousRequest(NetworkResourceLoader::SynchronousLoadData& data, const SharedBuffer* buffer, const NetworkLoadMetrics& metrics)
90
static void sendReplyToSynchronousRequest(NetworkResourceLoader::SynchronousLoadData& data, const FragmentedSharedBuffer* buffer, const NetworkLoadMetrics& metrics)
91
{
91
{
92
    ASSERT(data.delayedReply);
92
    ASSERT(data.delayedReply);
93
    ASSERT(!data.response.isNull() || !data.error.isNull());
93
    ASSERT(!data.response.isNull() || !data.error.isNull());
94
94
95
    Vector<uint8_t> responseBuffer;
95
    Vector<uint8_t> responseBuffer;
96
    if (buffer && buffer->size())
96
    if (buffer && buffer->size())
97
        responseBuffer.append(buffer->data(), buffer->size());
97
        responseBuffer.append(buffer->makeContiguous()->data(), buffer->size());
98
98
99
    data.response.setDeprecatedNetworkLoadMetrics(Box<NetworkLoadMetrics>::create(metrics));
99
    data.response.setDeprecatedNetworkLoadMetrics(Box<NetworkLoadMetrics>::create(metrics));
100
100
Lines 105-113 static void sendReplyToSynchronousRequest(NetworkResourceLoader::SynchronousLoad a/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp_sec2
105
NetworkResourceLoader::NetworkResourceLoader(NetworkResourceLoadParameters&& parameters, NetworkConnectionToWebProcess& connection, Messages::NetworkConnectionToWebProcess::PerformSynchronousLoad::DelayedReply&& synchronousReply)
105
NetworkResourceLoader::NetworkResourceLoader(NetworkResourceLoadParameters&& parameters, NetworkConnectionToWebProcess& connection, Messages::NetworkConnectionToWebProcess::PerformSynchronousLoad::DelayedReply&& synchronousReply)
106
    : m_parameters { WTFMove(parameters) }
106
    : m_parameters { WTFMove(parameters) }
107
    , m_connection { connection }
107
    , m_connection { connection }
108
    , m_bufferedData { makeUniqueRef<SharedBufferBuilder>() }
108
    , m_fileReferences(connection.resolveBlobReferences(m_parameters))
109
    , m_fileReferences(connection.resolveBlobReferences(m_parameters))
109
    , m_isAllowedToAskUserForCredentials { m_parameters.clientCredentialPolicy == ClientCredentialPolicy::MayAskClientForCredentials }
110
    , m_isAllowedToAskUserForCredentials { m_parameters.clientCredentialPolicy == ClientCredentialPolicy::MayAskClientForCredentials }
110
    , m_bufferingTimer { *this, &NetworkResourceLoader::bufferingTimerFired }
111
    , m_bufferingTimer { *this, &NetworkResourceLoader::bufferingTimerFired }
112
    , m_bufferedDataForCache { makeUniqueRef<SharedBufferBuilder>() }
111
    , m_shouldCaptureExtraNetworkLoadMetrics(m_connection->captureExtraNetworkLoadMetricsEnabled())
113
    , m_shouldCaptureExtraNetworkLoadMetrics(m_connection->captureExtraNetworkLoadMetricsEnabled())
112
    , m_resourceLoadID { NetworkResourceLoadIdentifier::generate() }
114
    , m_resourceLoadID { NetworkResourceLoadIdentifier::generate() }
113
{
115
{
Lines 306-315 void NetworkResourceLoader::startNetworkLoad(ResourceRequest&& request, FirstLoa a/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp_sec3
306
        consumeSandboxExtensions();
308
        consumeSandboxExtensions();
307
309
308
        if (isSynchronous() || m_parameters.maximumBufferingTime > 0_s)
310
        if (isSynchronous() || m_parameters.maximumBufferingTime > 0_s)
309
            m_bufferedData = SharedBuffer::create();
311
            m_bufferedData->empty();
310
312
311
        if (canUseCache(request))
313
        if (canUseCache(request))
312
            m_bufferedDataForCache = SharedBuffer::create();
314
            m_bufferedDataForCache->empty();
313
    }
315
    }
314
316
315
    NetworkLoadParameters parameters = m_parameters;
317
    NetworkLoadParameters parameters = m_parameters;
Lines 730-749 void NetworkResourceLoader::didReceiveResponse(ResourceResponse&& receivedRespon a/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp_sec4
730
            || equalLettersIgnoringASCIICase(mimeType, "application/octet-stream");
732
            || equalLettersIgnoringASCIICase(mimeType, "application/octet-stream");
731
    };
733
    };
732
734
733
    if (!m_bufferedData
735
    if (m_bufferedData->isNull()
734
        && m_response.expectedContentLength() > static_cast<long long>(1 * MB)
736
        && m_response.expectedContentLength() > static_cast<long long>(1 * MB)
735
        && isFetchOrXHR(resourceLoadInfo)
737
        && isFetchOrXHR(resourceLoadInfo)
736
        && isMediaMIMEType(m_response.mimeType())) {
738
        && isMediaMIMEType(m_response.mimeType())) {
737
        m_bufferedData = SharedBuffer::create();
739
        m_bufferedData->empty();
738
        m_parameters.maximumBufferingTime = WebLoaderStrategy::mediaMaximumBufferingTime;
740
        m_parameters.maximumBufferingTime = WebLoaderStrategy::mediaMaximumBufferingTime;
739
    }
741
    }
740
742
741
    // For multipart/x-mixed-replace didReceiveResponseAsync gets called multiple times and buffering would require special handling.
743
    // For multipart/x-mixed-replace didReceiveResponseAsync gets called multiple times and buffering would require special handling.
742
    if (!isSynchronous() && m_response.isMultipart())
744
    if (!isSynchronous() && m_response.isMultipart())
743
        m_bufferedData = nullptr;
745
        m_bufferedData->reset();
744
746
745
    if (m_response.isMultipart())
747
    if (m_response.isMultipart())
746
        m_bufferedDataForCache = nullptr;
748
        m_bufferedDataForCache->reset();
747
749
748
    if (m_cacheEntryForValidation) {
750
    if (m_cacheEntryForValidation) {
749
        bool validationSucceeded = m_response.httpStatusCode() == 304; // 304 Not Modified
751
        bool validationSucceeded = m_response.httpStatusCode() == 304; // 304 Not Modified
Lines 858-864 void NetworkResourceLoader::sendDidReceiveResponsePotentiallyInNewBrowsingContex a/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp_sec5
858
    });
860
    });
859
}
861
}
860
862
861
void NetworkResourceLoader::didReceiveBuffer(Ref<SharedBuffer>&& buffer, int reportedEncodedDataLength)
863
void NetworkResourceLoader::didReceiveBuffer(Ref<FragmentedSharedBuffer>&& buffer, int reportedEncodedDataLength)
862
{
864
{
863
    if (!m_numBytesReceived)
865
    if (!m_numBytesReceived)
864
        LOADER_RELEASE_LOG("didReceiveBuffer: Started receiving data (reportedEncodedDataLength=%d)", reportedEncodedDataLength);
866
        LOADER_RELEASE_LOG("didReceiveBuffer: Started receiving data (reportedEncodedDataLength=%d)", reportedEncodedDataLength);
Lines 866-885 void NetworkResourceLoader::didReceiveBuffer(Ref<SharedBuffer>&& buffer, int rep a/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp_sec6
866
868
867
    ASSERT(!m_cacheEntryForValidation);
869
    ASSERT(!m_cacheEntryForValidation);
868
870
869
    if (m_bufferedDataForCache) {
871
    if (!m_bufferedDataForCache->isNull()) {
870
        // Prevent memory growth in case of streaming data and limit size of entries in the cache.
872
        // Prevent memory growth in case of streaming data and limit size of entries in the cache.
871
        const size_t maximumCacheBufferSize = m_cache->capacity() / 8;
873
        const size_t maximumCacheBufferSize = m_cache->capacity() / 8;
872
        if (m_bufferedDataForCache->size() + buffer->size() <= maximumCacheBufferSize)
874
        if (m_bufferedDataForCache->size() + buffer->size() <= maximumCacheBufferSize)
873
            m_bufferedDataForCache->append(buffer.get());
875
            m_bufferedDataForCache->append(buffer.get());
874
        else
876
        else
875
            m_bufferedDataForCache = nullptr;
877
            m_bufferedDataForCache->reset();
876
    }
878
    }
877
    if (isCrossOriginPrefetch())
879
    if (isCrossOriginPrefetch())
878
        return;
880
        return;
879
    // FIXME: At least on OS X Yosemite we always get -1 from the resource handle.
881
    // FIXME: At least on OS X Yosemite we always get -1 from the resource handle.
880
    unsigned encodedDataLength = reportedEncodedDataLength >= 0 ? reportedEncodedDataLength : buffer->size();
882
    unsigned encodedDataLength = reportedEncodedDataLength >= 0 ? reportedEncodedDataLength : buffer->size();
881
883
882
    if (m_bufferedData) {
884
    if (!m_bufferedData->isNull()) {
883
        m_bufferedData->append(buffer.get());
885
        m_bufferedData->append(buffer.get());
884
        m_bufferedDataEncodedDataLength += encodedDataLength;
886
        m_bufferedDataEncodedDataLength += encodedDataLength;
885
        startBufferingTimerIfNeeded();
887
        startBufferingTimerIfNeeded();
Lines 909-919 void NetworkResourceLoader::didFinishLoading(const NetworkLoadMetrics& networkLo a/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp_sec7
909
#endif
911
#endif
910
912
911
    if (isSynchronous())
913
    if (isSynchronous())
912
        sendReplyToSynchronousRequest(*m_synchronousLoadData, m_bufferedData.get(), networkLoadMetrics);
914
        sendReplyToSynchronousRequest(*m_synchronousLoadData, m_bufferedData->get().get(), networkLoadMetrics);
913
    else {
915
    else {
914
        if (m_bufferedData && !m_bufferedData->isEmpty()) {
916
        if (!m_bufferedData->isEmpty()) {
915
            // FIXME: Pass a real value or remove the encoded data size feature.
917
            // FIXME: Pass a real value or remove the encoded data size feature.
916
            sendBuffer(*m_bufferedData, -1);
918
            sendBuffer(*m_bufferedData->get(), -1);
917
        }
919
        }
918
        send(Messages::WebResourceLoader::DidFinishResourceLoad(networkLoadMetrics));
920
        send(Messages::WebResourceLoader::DidFinishResourceLoad(networkLoadMetrics));
919
    }
921
    }
Lines 1256-1274 void NetworkResourceLoader::startBufferingTimerIfNeeded() a/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp_sec8
1256
1258
1257
void NetworkResourceLoader::bufferingTimerFired()
1259
void NetworkResourceLoader::bufferingTimerFired()
1258
{
1260
{
1259
    ASSERT(m_bufferedData);
1261
    ASSERT(!m_bufferedData->isNull());
1260
    ASSERT(m_networkLoad);
1262
    ASSERT(m_networkLoad);
1261
1263
1262
    if (m_bufferedData->isEmpty())
1264
    if (m_bufferedData->isEmpty())
1263
        return;
1265
        return;
1264
1266
1265
    send(Messages::WebResourceLoader::DidReceiveData({ *m_bufferedData }, m_bufferedDataEncodedDataLength));
1267
    send(Messages::WebResourceLoader::DidReceiveData({ *m_bufferedData->get() }, m_bufferedDataEncodedDataLength));
1266
1268
1267
    m_bufferedData = SharedBuffer::create();
1269
    m_bufferedData->empty();
1268
    m_bufferedDataEncodedDataLength = 0;
1270
    m_bufferedDataEncodedDataLength = 0;
1269
}
1271
}
1270
1272
1271
void NetworkResourceLoader::sendBuffer(SharedBuffer& buffer, size_t encodedDataLength)
1273
void NetworkResourceLoader::sendBuffer(FragmentedSharedBuffer& buffer, size_t encodedDataLength)
1272
{
1274
{
1273
    ASSERT(!isSynchronous());
1275
    ASSERT(!isSynchronous());
1274
1276
Lines 1281-1287 void NetworkResourceLoader::tryStoreAsCacheEntry() a/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp_sec9
1281
        LOADER_RELEASE_LOG("tryStoreAsCacheEntry: Not storing cache entry because request is not eligible");
1283
        LOADER_RELEASE_LOG("tryStoreAsCacheEntry: Not storing cache entry because request is not eligible");
1282
        return;
1284
        return;
1283
    }
1285
    }
1284
    if (!m_bufferedDataForCache) {
1286
    if (m_bufferedDataForCache->isNull()) {
1285
        LOADER_RELEASE_LOG("tryStoreAsCacheEntry: Not storing cache entry because m_bufferedDataForCache is null");
1287
        LOADER_RELEASE_LOG("tryStoreAsCacheEntry: Not storing cache entry because m_bufferedDataForCache is null");
1286
        return;
1288
        return;
1287
    }
1289
    }
Lines 1289-1300 void NetworkResourceLoader::tryStoreAsCacheEntry() a/Source/WebKit/NetworkProcess/NetworkResourceLoader.cpp_sec10
1289
    if (isCrossOriginPrefetch()) {
1291
    if (isCrossOriginPrefetch()) {
1290
        if (auto* session = m_connection->networkProcess().networkSession(sessionID())) {
1292
        if (auto* session = m_connection->networkProcess().networkSession(sessionID())) {
1291
            LOADER_RELEASE_LOG("tryStoreAsCacheEntry: Storing entry in prefetch cache");
1293
            LOADER_RELEASE_LOG("tryStoreAsCacheEntry: Storing entry in prefetch cache");
1292
            session->prefetchCache().store(m_networkLoad->currentRequest().url(), WTFMove(m_response), WTFMove(m_bufferedDataForCache));
1294
            session->prefetchCache().store(m_networkLoad->currentRequest().url(), WTFMove(m_response), m_bufferedDataForCache->take());
1293
        }
1295
        }
1294
        return;
1296
        return;
1295
    }
1297
    }
1296
    LOADER_RELEASE_LOG("tryStoreAsCacheEntry: Storing entry in HTTP disk cache");
1298
    LOADER_RELEASE_LOG("tryStoreAsCacheEntry: Storing entry in HTTP disk cache");
1297
    m_cache->store(m_networkLoad->currentRequest(), m_response, WTFMove(m_bufferedDataForCache), [loader = Ref { *this }](auto& mappedBody) mutable {
1299
    m_cache->store(m_networkLoad->currentRequest(), m_response, m_bufferedDataForCache->take(), [loader = Ref { *this }](auto& mappedBody) mutable {
1298
#if ENABLE(SHAREABLE_RESOURCE)
1300
#if ENABLE(SHAREABLE_RESOURCE)
1299
        if (mappedBody.shareableResourceHandle.isNull())
1301
        if (mappedBody.shareableResourceHandle.isNull())
1300
            return;
1302
            return;
- a/Source/WebKit/NetworkProcess/NetworkResourceLoader.h -4 / +7 lines
Lines 39-44 a/Source/WebKit/NetworkProcess/NetworkResourceLoader.h_sec1
39
#include <WebCore/ResourceResponse.h>
39
#include <WebCore/ResourceResponse.h>
40
#include <WebCore/SecurityPolicyViolationEvent.h>
40
#include <WebCore/SecurityPolicyViolationEvent.h>
41
#include <WebCore/Timer.h>
41
#include <WebCore/Timer.h>
42
#include <wtf/UniqueRef.h>
42
#include <wtf/WeakPtr.h>
43
#include <wtf/WeakPtr.h>
43
44
44
namespace WebCore {
45
namespace WebCore {
Lines 46-51 class BlobDataFileReference; a/Source/WebKit/NetworkProcess/NetworkResourceLoader.h_sec2
46
class FormData;
47
class FormData;
47
class NetworkStorageSession;
48
class NetworkStorageSession;
48
class ResourceRequest;
49
class ResourceRequest;
50
class FragmentedSharedBuffer;
51
class SharedBufferBuilder;
49
}
52
}
50
53
51
namespace WebKit {
54
namespace WebKit {
Lines 114-120 public: a/Source/WebKit/NetworkProcess/NetworkResourceLoader.h_sec3
114
    bool isAllowedToAskUserForCredentials() const final { return m_isAllowedToAskUserForCredentials; }
117
    bool isAllowedToAskUserForCredentials() const final { return m_isAllowedToAskUserForCredentials; }
115
    void willSendRedirectedRequest(WebCore::ResourceRequest&&, WebCore::ResourceRequest&& redirectRequest, WebCore::ResourceResponse&&) final;
118
    void willSendRedirectedRequest(WebCore::ResourceRequest&&, WebCore::ResourceRequest&& redirectRequest, WebCore::ResourceResponse&&) final;
116
    void didReceiveResponse(WebCore::ResourceResponse&&, ResponseCompletionHandler&&) final;
119
    void didReceiveResponse(WebCore::ResourceResponse&&, ResponseCompletionHandler&&) final;
117
    void didReceiveBuffer(Ref<WebCore::SharedBuffer>&&, int reportedEncodedDataLength) final;
120
    void didReceiveBuffer(Ref<WebCore::FragmentedSharedBuffer>&&, int reportedEncodedDataLength) final;
118
    void didFinishLoading(const WebCore::NetworkLoadMetrics&) final;
121
    void didFinishLoading(const WebCore::NetworkLoadMetrics&) final;
119
    void didFailLoading(const WebCore::ResourceError&) final;
122
    void didFailLoading(const WebCore::ResourceError&) final;
120
    void didBlockAuthenticationChallenge() final;
123
    void didBlockAuthenticationChallenge() final;
Lines 192-198 private: a/Source/WebKit/NetworkProcess/NetworkResourceLoader.h_sec4
192
195
193
    void startBufferingTimerIfNeeded();
196
    void startBufferingTimerIfNeeded();
194
    void bufferingTimerFired();
197
    void bufferingTimerFired();
195
    void sendBuffer(WebCore::SharedBuffer&, size_t encodedDataLength);
198
    void sendBuffer(WebCore::FragmentedSharedBuffer&, size_t encodedDataLength);
196
199
197
    void consumeSandboxExtensions();
200
    void consumeSandboxExtensions();
198
    void invalidateSandboxExtensions();
201
    void invalidateSandboxExtensions();
Lines 225-231 private: a/Source/WebKit/NetworkProcess/NetworkResourceLoader.h_sec5
225
    WebCore::ResourceResponse m_response;
228
    WebCore::ResourceResponse m_response;
226
229
227
    size_t m_bufferedDataEncodedDataLength { 0 };
230
    size_t m_bufferedDataEncodedDataLength { 0 };
228
    RefPtr<WebCore::SharedBuffer> m_bufferedData;
231
    UniqueRef<WebCore::SharedBufferBuilder> m_bufferedData;
229
    unsigned m_redirectCount { 0 };
232
    unsigned m_redirectCount { 0 };
230
233
231
    std::unique_ptr<SynchronousLoadData> m_synchronousLoadData;
234
    std::unique_ptr<SynchronousLoadData> m_synchronousLoadData;
Lines 240-246 private: a/Source/WebKit/NetworkProcess/NetworkResourceLoader.h_sec6
240
243
241
    WebCore::Timer m_bufferingTimer;
244
    WebCore::Timer m_bufferingTimer;
242
    RefPtr<NetworkCache::Cache> m_cache;
245
    RefPtr<NetworkCache::Cache> m_cache;
243
    RefPtr<WebCore::SharedBuffer> m_bufferedDataForCache;
246
    UniqueRef<WebCore::SharedBufferBuilder> m_bufferedDataForCache;
244
    std::unique_ptr<NetworkCache::Entry> m_cacheEntryForValidation;
247
    std::unique_ptr<NetworkCache::Entry> m_cacheEntryForValidation;
245
    std::unique_ptr<NetworkCache::Entry> m_cacheEntryForMaxAgeCapValidation;
248
    std::unique_ptr<NetworkCache::Entry> m_cacheEntryForMaxAgeCapValidation;
246
    bool m_isWaitingContinueWillSendRequestForCachedRedirect { false };
249
    bool m_isWaitingContinueWillSendRequestForCachedRedirect { false };
- a/Source/WebKit/NetworkProcess/PingLoad.cpp -1 / +1 lines
Lines 172-178 void PingLoad::didReceiveResponse(ResourceResponse&& response, NegotiatedLegacyT a/Source/WebKit/NetworkProcess/PingLoad.cpp_sec1
172
    didFinish({ }, response);
172
    didFinish({ }, response);
173
}
173
}
174
174
175
void PingLoad::didReceiveData(Ref<SharedBuffer>&&)
175
void PingLoad::didReceiveData(Ref<FragmentedSharedBuffer>&&)
176
{
176
{
177
    PING_RELEASE_LOG("didReceiveData");
177
    PING_RELEASE_LOG("didReceiveData");
178
    ASSERT_NOT_REACHED();
178
    ASSERT_NOT_REACHED();
- a/Source/WebKit/NetworkProcess/PingLoad.h -1 / +1 lines
Lines 54-60 private: a/Source/WebKit/NetworkProcess/PingLoad.h_sec1
54
    void willPerformHTTPRedirection(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&, RedirectCompletionHandler&&) final;
54
    void willPerformHTTPRedirection(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&, RedirectCompletionHandler&&) final;
55
    void didReceiveChallenge(WebCore::AuthenticationChallenge&&, NegotiatedLegacyTLS, ChallengeCompletionHandler&&) final;
55
    void didReceiveChallenge(WebCore::AuthenticationChallenge&&, NegotiatedLegacyTLS, ChallengeCompletionHandler&&) final;
56
    void didReceiveResponse(WebCore::ResourceResponse&&, NegotiatedLegacyTLS, ResponseCompletionHandler&&) final;
56
    void didReceiveResponse(WebCore::ResourceResponse&&, NegotiatedLegacyTLS, ResponseCompletionHandler&&) final;
57
    void didReceiveData(Ref<WebCore::SharedBuffer>&&) final;
57
    void didReceiveData(Ref<WebCore::FragmentedSharedBuffer>&&) final;
58
    void didCompleteWithError(const WebCore::ResourceError&, const WebCore::NetworkLoadMetrics&) final;
58
    void didCompleteWithError(const WebCore::ResourceError&, const WebCore::NetworkLoadMetrics&) final;
59
    void didSendData(uint64_t totalBytesSent, uint64_t totalBytesExpectedToSend) final;
59
    void didSendData(uint64_t totalBytesSent, uint64_t totalBytesExpectedToSend) final;
60
    void wasBlocked() final;
60
    void wasBlocked() final;
- a/Source/WebKit/NetworkProcess/PreconnectTask.cpp -1 / +1 lines
Lines 79-85 void PreconnectTask::didReceiveResponse(ResourceResponse&& response, ResponseCom a/Source/WebKit/NetworkProcess/PreconnectTask.cpp_sec1
79
    completionHandler(PolicyAction::Ignore);
79
    completionHandler(PolicyAction::Ignore);
80
}
80
}
81
81
82
void PreconnectTask::didReceiveBuffer(Ref<SharedBuffer>&&, int reportedEncodedDataLength)
82
void PreconnectTask::didReceiveBuffer(Ref<FragmentedSharedBuffer>&&, int reportedEncodedDataLength)
83
{
83
{
84
    ASSERT_NOT_REACHED();
84
    ASSERT_NOT_REACHED();
85
}
85
}
- a/Source/WebKit/NetworkProcess/PreconnectTask.h -1 / +1 lines
Lines 55-61 private: a/Source/WebKit/NetworkProcess/PreconnectTask.h_sec1
55
    void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent) final;
55
    void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent) final;
56
    void willSendRedirectedRequest(WebCore::ResourceRequest&&, WebCore::ResourceRequest&& redirectRequest, WebCore::ResourceResponse&& redirectResponse) final;
56
    void willSendRedirectedRequest(WebCore::ResourceRequest&&, WebCore::ResourceRequest&& redirectRequest, WebCore::ResourceResponse&& redirectResponse) final;
57
    void didReceiveResponse(WebCore::ResourceResponse&&, ResponseCompletionHandler&&) final;
57
    void didReceiveResponse(WebCore::ResourceResponse&&, ResponseCompletionHandler&&) final;
58
    void didReceiveBuffer(Ref<WebCore::SharedBuffer>&&, int reportedEncodedDataLength) final;
58
    void didReceiveBuffer(Ref<WebCore::FragmentedSharedBuffer>&&, int reportedEncodedDataLength) final;
59
    void didFinishLoading(const WebCore::NetworkLoadMetrics&) final;
59
    void didFinishLoading(const WebCore::NetworkLoadMetrics&) final;
60
    void didFailLoading(const WebCore::ResourceError&) final;
60
    void didFailLoading(const WebCore::ResourceError&) final;
61
61
- a/Source/WebKit/NetworkProcess/ServiceWorker/ServiceWorkerNavigationPreloader.cpp -2 / +2 lines
Lines 174-183 void ServiceWorkerNavigationPreloader::didReceiveResponse(ResourceResponse&& res a/Source/WebKit/NetworkProcess/ServiceWorker/ServiceWorkerNavigationPreloader.cpp_sec1
174
        callback();
174
        callback();
175
}
175
}
176
176
177
void ServiceWorkerNavigationPreloader::didReceiveBuffer(Ref<SharedBuffer>&& buffer, int reportedEncodedDataLength)
177
void ServiceWorkerNavigationPreloader::didReceiveBuffer(Ref<FragmentedSharedBuffer>&& buffer, int reportedEncodedDataLength)
178
{
178
{
179
    if (m_bodyCallback)
179
    if (m_bodyCallback)
180
        m_bodyCallback(WTFMove(buffer), reportedEncodedDataLength);
180
        m_bodyCallback(buffer->makeContiguous(), reportedEncodedDataLength);
181
}
181
}
182
182
183
void ServiceWorkerNavigationPreloader::didFinishLoading(const NetworkLoadMetrics& networkLoadMetrics)
183
void ServiceWorkerNavigationPreloader::didFinishLoading(const NetworkLoadMetrics& networkLoadMetrics)
- a/Source/WebKit/NetworkProcess/ServiceWorker/ServiceWorkerNavigationPreloader.h -1 / +1 lines
Lines 67-73 private: a/Source/WebKit/NetworkProcess/ServiceWorker/ServiceWorkerNavigationPreloader.h_sec1
67
    bool isAllowedToAskUserForCredentials() const final { return false; }
67
    bool isAllowedToAskUserForCredentials() const final { return false; }
68
    void willSendRedirectedRequest(WebCore::ResourceRequest&&, WebCore::ResourceRequest&& redirectRequest, WebCore::ResourceResponse&& redirectResponse) final;
68
    void willSendRedirectedRequest(WebCore::ResourceRequest&&, WebCore::ResourceRequest&& redirectRequest, WebCore::ResourceResponse&& redirectResponse) final;
69
    void didReceiveResponse(WebCore::ResourceResponse&&, ResponseCompletionHandler&&) final;
69
    void didReceiveResponse(WebCore::ResourceResponse&&, ResponseCompletionHandler&&) final;
70
    void didReceiveBuffer(Ref<WebCore::SharedBuffer>&&, int reportedEncodedDataLength) final;
70
    void didReceiveBuffer(Ref<WebCore::FragmentedSharedBuffer>&&, int reportedEncodedDataLength) final;
71
    void didFinishLoading(const WebCore::NetworkLoadMetrics&) final;
71
    void didFinishLoading(const WebCore::NetworkLoadMetrics&) final;
72
    void didFailLoading(const WebCore::ResourceError&) final;
72
    void didFailLoading(const WebCore::ResourceError&) final;
73
    bool shouldCaptureExtraNetworkLoadMetrics() const final { return m_shouldCaptureExtraNetworkLoadMetrics; }
73
    bool shouldCaptureExtraNetworkLoadMetrics() const final { return m_shouldCaptureExtraNetworkLoadMetrics; }
- a/Source/WebKit/NetworkProcess/ServiceWorker/ServiceWorkerSoftUpdateLoader.cpp -2 / +2 lines
Lines 177-183 ResourceError ServiceWorkerSoftUpdateLoader::processResponse(const ResourceRespo a/Source/WebKit/NetworkProcess/ServiceWorker/ServiceWorkerSoftUpdateLoader.cpp_sec1
177
    return { };
177
    return { };
178
}
178
}
179
179
180
void ServiceWorkerSoftUpdateLoader::didReceiveBuffer(Ref<SharedBuffer>&& buffer, int reportedEncodedDataLength)
180
void ServiceWorkerSoftUpdateLoader::didReceiveBuffer(Ref<FragmentedSharedBuffer>&& buffer, int reportedEncodedDataLength)
181
{
181
{
182
    if (!m_decoder) {
182
    if (!m_decoder) {
183
        if (!m_responseEncoding.isEmpty())
183
        if (!m_responseEncoding.isEmpty())
Lines 187-193 void ServiceWorkerSoftUpdateLoader::didReceiveBuffer(Ref<SharedBuffer>&& buffer, a/Source/WebKit/NetworkProcess/ServiceWorker/ServiceWorkerSoftUpdateLoader.cpp_sec2
187
    }
187
    }
188
188
189
    if (auto size = buffer->size())
189
    if (auto size = buffer->size())
190
        m_script.append(m_decoder->decode(buffer->data(), size));
190
        m_script.append(m_decoder->decode(buffer->makeContiguous()->data(), size));
191
}
191
}
192
192
193
void ServiceWorkerSoftUpdateLoader::didFinishLoading(const WebCore::NetworkLoadMetrics&)
193
void ServiceWorkerSoftUpdateLoader::didFinishLoading(const WebCore::NetworkLoadMetrics&)
- a/Source/WebKit/NetworkProcess/ServiceWorker/ServiceWorkerSoftUpdateLoader.h -1 / +1 lines
Lines 64-70 private: a/Source/WebKit/NetworkProcess/ServiceWorker/ServiceWorkerSoftUpdateLoader.h_sec1
64
    bool isAllowedToAskUserForCredentials() const final { return false; }
64
    bool isAllowedToAskUserForCredentials() const final { return false; }
65
    void willSendRedirectedRequest(WebCore::ResourceRequest&&, WebCore::ResourceRequest&& redirectRequest, WebCore::ResourceResponse&& redirectResponse) final;
65
    void willSendRedirectedRequest(WebCore::ResourceRequest&&, WebCore::ResourceRequest&& redirectRequest, WebCore::ResourceResponse&& redirectResponse) final;
66
    void didReceiveResponse(WebCore::ResourceResponse&&, ResponseCompletionHandler&&) final;
66
    void didReceiveResponse(WebCore::ResourceResponse&&, ResponseCompletionHandler&&) final;
67
    void didReceiveBuffer(Ref<WebCore::SharedBuffer>&&, int reportedEncodedDataLength) final;
67
    void didReceiveBuffer(Ref<WebCore::FragmentedSharedBuffer>&&, int reportedEncodedDataLength) final;
68
    void didFinishLoading(const WebCore::NetworkLoadMetrics&) final;
68
    void didFinishLoading(const WebCore::NetworkLoadMetrics&) final;
69
    void didFailLoading(const WebCore::ResourceError&) final;
69
    void didFailLoading(const WebCore::ResourceError&) final;
70
70
- a/Source/WebKit/NetworkProcess/cache/NetworkCache.cpp -2 / +2 lines
Lines 454-460 void Cache::completeRetrieve(RetrieveCompletionHandler&& handler, std::unique_pt a/Source/WebKit/NetworkProcess/cache/NetworkCache.cpp_sec1
454
    handler(WTFMove(entry), info);
454
    handler(WTFMove(entry), info);
455
}
455
}
456
    
456
    
457
std::unique_ptr<Entry> Cache::makeEntry(const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, RefPtr<WebCore::SharedBuffer>&& responseData)
457
std::unique_ptr<Entry> Cache::makeEntry(const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, RefPtr<WebCore::FragmentedSharedBuffer>&& responseData)
458
{
458
{
459
    return makeUnique<Entry>(makeCacheKey(request), response, WTFMove(responseData), WebCore::collectVaryingRequestHeaders(networkProcess().storageSession(m_sessionID), request, response));
459
    return makeUnique<Entry>(makeCacheKey(request), response, WTFMove(responseData), WebCore::collectVaryingRequestHeaders(networkProcess().storageSession(m_sessionID), request, response));
460
}
460
}
Lines 464-470 std::unique_ptr<Entry> Cache::makeRedirectEntry(const WebCore::ResourceRequest& a/Source/WebKit/NetworkProcess/cache/NetworkCache.cpp_sec2
464
    return makeUnique<Entry>(makeCacheKey(request), response, redirectRequest, WebCore::collectVaryingRequestHeaders(networkProcess().storageSession(m_sessionID), request, response));
464
    return makeUnique<Entry>(makeCacheKey(request), response, redirectRequest, WebCore::collectVaryingRequestHeaders(networkProcess().storageSession(m_sessionID), request, response));
465
}
465
}
466
466
467
std::unique_ptr<Entry> Cache::store(const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, RefPtr<WebCore::SharedBuffer>&& responseData, Function<void(MappedBody&)>&& completionHandler)
467
std::unique_ptr<Entry> Cache::store(const WebCore::ResourceRequest& request, const WebCore::ResourceResponse& response, RefPtr<WebCore::FragmentedSharedBuffer>&& responseData, Function<void(MappedBody&)>&& completionHandler)
468
{
468
{
469
    ASSERT(responseData);
469
    ASSERT(responseData);
470
470
- a/Source/WebKit/NetworkProcess/cache/NetworkCache.h -3 / +3 lines
Lines 43-49 a/Source/WebKit/NetworkProcess/cache/NetworkCache.h_sec1
43
namespace WebCore {
43
namespace WebCore {
44
class LowPowerModeNotifier;
44
class LowPowerModeNotifier;
45
class ResourceRequest;
45
class ResourceRequest;
46
class SharedBuffer;
46
class FragmentedSharedBuffer;
47
}
47
}
48
48
49
namespace WebKit {
49
namespace WebKit {
Lines 166-172 public: a/Source/WebKit/NetworkProcess/cache/NetworkCache.h_sec2
166
    };
166
    };
167
    using RetrieveCompletionHandler = Function<void(std::unique_ptr<Entry>, const RetrieveInfo&)>;
167
    using RetrieveCompletionHandler = Function<void(std::unique_ptr<Entry>, const RetrieveInfo&)>;
168
    void retrieve(const WebCore::ResourceRequest&, const GlobalFrameID&, std::optional<NavigatingToAppBoundDomain>, RetrieveCompletionHandler&&);
168
    void retrieve(const WebCore::ResourceRequest&, const GlobalFrameID&, std::optional<NavigatingToAppBoundDomain>, RetrieveCompletionHandler&&);
169
    std::unique_ptr<Entry> store(const WebCore::ResourceRequest&, const WebCore::ResourceResponse&, RefPtr<WebCore::SharedBuffer>&&, Function<void(MappedBody&)>&& = nullptr);
169
    std::unique_ptr<Entry> store(const WebCore::ResourceRequest&, const WebCore::ResourceResponse&, RefPtr<WebCore::FragmentedSharedBuffer>&&, Function<void(MappedBody&)>&& = nullptr);
170
    std::unique_ptr<Entry> storeRedirect(const WebCore::ResourceRequest&, const WebCore::ResourceResponse&, const WebCore::ResourceRequest& redirectRequest, std::optional<Seconds> maxAgeCap);
170
    std::unique_ptr<Entry> storeRedirect(const WebCore::ResourceRequest&, const WebCore::ResourceResponse&, const WebCore::ResourceRequest& redirectRequest, std::optional<Seconds> maxAgeCap);
171
    std::unique_ptr<Entry> update(const WebCore::ResourceRequest&, const Entry&, const WebCore::ResourceResponse& validatingResponse);
171
    std::unique_ptr<Entry> update(const WebCore::ResourceRequest&, const Entry&, const WebCore::ResourceResponse& validatingResponse);
172
172
Lines 185-191 public: a/Source/WebKit/NetworkProcess/cache/NetworkCache.h_sec3
185
    void retrieveData(const DataKey&, Function<void(const uint8_t*, size_t)>);
185
    void retrieveData(const DataKey&, Function<void(const uint8_t*, size_t)>);
186
    void storeData(const DataKey&,  const uint8_t* data, size_t);
186
    void storeData(const DataKey&,  const uint8_t* data, size_t);
187
    
187
    
188
    std::unique_ptr<Entry> makeEntry(const WebCore::ResourceRequest&, const WebCore::ResourceResponse&, RefPtr<WebCore::SharedBuffer>&&);
188
    std::unique_ptr<Entry> makeEntry(const WebCore::ResourceRequest&, const WebCore::ResourceResponse&, RefPtr<WebCore::FragmentedSharedBuffer>&&);
189
    std::unique_ptr<Entry> makeRedirectEntry(const WebCore::ResourceRequest&, const WebCore::ResourceResponse&, const WebCore::ResourceRequest& redirectRequest);
189
    std::unique_ptr<Entry> makeRedirectEntry(const WebCore::ResourceRequest&, const WebCore::ResourceResponse&, const WebCore::ResourceRequest& redirectRequest);
190
190
191
    void dumpContentsToFile();
191
    void dumpContentsToFile();
- a/Source/WebKit/NetworkProcess/cache/NetworkCacheEntry.cpp -4 / +6 lines
Lines 37-43 a/Source/WebKit/NetworkProcess/cache/NetworkCacheEntry.cpp_sec1
37
namespace WebKit {
37
namespace WebKit {
38
namespace NetworkCache {
38
namespace NetworkCache {
39
39
40
Entry::Entry(const Key& key, const WebCore::ResourceResponse& response, RefPtr<WebCore::SharedBuffer>&& buffer, const Vector<std::pair<String, String>>& varyingRequestHeaders)
40
Entry::Entry(const Key& key, const WebCore::ResourceResponse& response, RefPtr<WebCore::FragmentedSharedBuffer>&& buffer, const Vector<std::pair<String, String>>& varyingRequestHeaders)
41
    : m_key(key)
41
    : m_key(key)
42
    , m_timeStamp(WallTime::now())
42
    , m_timeStamp(WallTime::now())
43
    , m_response(response)
43
    , m_response(response)
Lines 101-108 Storage::Record Entry::encodeAsStorageRecord() const a/Source/WebKit/NetworkProcess/cache/NetworkCacheEntry.cpp_sec2
101
101
102
    Data header(encoder.buffer(), encoder.bufferSize());
102
    Data header(encoder.buffer(), encoder.bufferSize());
103
    Data body;
103
    Data body;
104
    if (m_buffer)
104
    if (m_buffer) {
105
        body = { m_buffer->data(), m_buffer->size() };
105
        m_buffer = m_buffer->makeContiguous();
106
        body = { static_cast<WebCore::SharedBuffer*>(m_buffer.get())->data(), m_buffer->size() };
107
    }
106
108
107
    return { m_key, m_timeStamp, header, body, { } };
109
    return { m_key, m_timeStamp, header, body, { } };
108
}
110
}
Lines 194-200 void Entry::initializeBufferFromStorageRecord() const a/Source/WebKit/NetworkProcess/cache/NetworkCacheEntry.cpp_sec3
194
    m_buffer = WebCore::SharedBuffer::create(m_sourceStorageRecord.body.data(), m_sourceStorageRecord.body.size());
196
    m_buffer = WebCore::SharedBuffer::create(m_sourceStorageRecord.body.data(), m_sourceStorageRecord.body.size());
195
}
197
}
196
198
197
WebCore::SharedBuffer* Entry::buffer() const
199
WebCore::FragmentedSharedBuffer* Entry::buffer() const
198
{
200
{
199
    if (!m_buffer)
201
    if (!m_buffer)
200
        initializeBufferFromStorageRecord();
202
        initializeBufferFromStorageRecord();
- a/Source/WebKit/NetworkProcess/cache/NetworkCacheEntry.h -4 / +4 lines
Lines 35-41 a/Source/WebKit/NetworkProcess/cache/NetworkCacheEntry.h_sec1
35
#include <wtf/text/WTFString.h>
35
#include <wtf/text/WTFString.h>
36
36
37
namespace WebCore {
37
namespace WebCore {
38
class SharedBuffer;
38
class FragmentedSharedBuffer;
39
}
39
}
40
40
41
namespace WebKit {
41
namespace WebKit {
Lines 44-50 namespace NetworkCache { a/Source/WebKit/NetworkProcess/cache/NetworkCacheEntry.h_sec2
44
class Entry {
44
class Entry {
45
    WTF_MAKE_FAST_ALLOCATED;
45
    WTF_MAKE_FAST_ALLOCATED;
46
public:
46
public:
47
    Entry(const Key&, const WebCore::ResourceResponse&, RefPtr<WebCore::SharedBuffer>&&, const Vector<std::pair<String, String>>& varyingRequestHeaders);
47
    Entry(const Key&, const WebCore::ResourceResponse&, RefPtr<WebCore::FragmentedSharedBuffer>&&, const Vector<std::pair<String, String>>& varyingRequestHeaders);
48
    Entry(const Key&, const WebCore::ResourceResponse&, const WebCore::ResourceRequest& redirectRequest, const Vector<std::pair<String, String>>& varyingRequestHeaders);
48
    Entry(const Key&, const WebCore::ResourceResponse&, const WebCore::ResourceRequest& redirectRequest, const Vector<std::pair<String, String>>& varyingRequestHeaders);
49
    explicit Entry(const Storage::Record&);
49
    explicit Entry(const Storage::Record&);
50
    Entry(const Entry&);
50
    Entry(const Entry&);
Lines 57-63 public: a/Source/WebKit/NetworkProcess/cache/NetworkCacheEntry.h_sec3
57
    const WebCore::ResourceResponse& response() const { return m_response; }
57
    const WebCore::ResourceResponse& response() const { return m_response; }
58
    const Vector<std::pair<String, String>>& varyingRequestHeaders() const { return m_varyingRequestHeaders; }
58
    const Vector<std::pair<String, String>>& varyingRequestHeaders() const { return m_varyingRequestHeaders; }
59
59
60
    WebCore::SharedBuffer* buffer() const;
60
    WebCore::FragmentedSharedBuffer* buffer() const;
61
    const std::optional<WebCore::ResourceRequest>& redirectRequest() const { return m_redirectRequest; }
61
    const std::optional<WebCore::ResourceRequest>& redirectRequest() const { return m_redirectRequest; }
62
62
63
#if ENABLE(SHAREABLE_RESOURCE)
63
#if ENABLE(SHAREABLE_RESOURCE)
Lines 88-94 private: a/Source/WebKit/NetworkProcess/cache/NetworkCacheEntry.h_sec4
88
    Vector<std::pair<String, String>> m_varyingRequestHeaders;
88
    Vector<std::pair<String, String>> m_varyingRequestHeaders;
89
89
90
    std::optional<WebCore::ResourceRequest> m_redirectRequest;
90
    std::optional<WebCore::ResourceRequest> m_redirectRequest;
91
    mutable RefPtr<WebCore::SharedBuffer> m_buffer;
91
    mutable RefPtr<WebCore::FragmentedSharedBuffer> m_buffer;
92
#if ENABLE(SHAREABLE_RESOURCE)
92
#if ENABLE(SHAREABLE_RESOURCE)
93
    mutable ShareableResource::Handle m_shareableResourceHandle;
93
    mutable ShareableResource::Handle m_shareableResourceHandle;
94
#endif
94
#endif
- a/Source/WebKit/NetworkProcess/cache/NetworkCacheSpeculativeLoad.cpp -8 / +8 lines
Lines 46-52 SpeculativeLoad::SpeculativeLoad(Cache& cache, const GlobalFrameID& globalFrameI a/Source/WebKit/NetworkProcess/cache/NetworkCacheSpeculativeLoad.cpp_sec1
46
    : m_cache(cache)
46
    : m_cache(cache)
47
    , m_completionHandler(WTFMove(completionHandler))
47
    , m_completionHandler(WTFMove(completionHandler))
48
    , m_originalRequest(request)
48
    , m_originalRequest(request)
49
    , m_bufferedDataForCache(SharedBuffer::create())
49
    , m_bufferedDataForCache(FragmentedSharedBuffer::create())
50
    , m_cacheEntry(WTFMove(cacheEntryForValidation))
50
    , m_cacheEntry(WTFMove(cacheEntryForValidation))
51
{
51
{
52
    ASSERT(!m_cacheEntry || m_cacheEntry->needsValidation());
52
    ASSERT(!m_cacheEntry || m_cacheEntry->needsValidation());
Lines 109-115 void SpeculativeLoad::didReceiveResponse(ResourceResponse&& receivedResponse, Re a/Source/WebKit/NetworkProcess/cache/NetworkCacheSpeculativeLoad.cpp_sec2
109
    m_response = receivedResponse;
109
    m_response = receivedResponse;
110
110
111
    if (m_response.isMultipart())
111
    if (m_response.isMultipart())
112
        m_bufferedDataForCache = nullptr;
112
        m_bufferedDataForCache.reset();
113
113
114
    bool validationSucceeded = m_response.httpStatusCode() == 304; // 304 Not Modified
114
    bool validationSucceeded = m_response.httpStatusCode() == 304; // 304 Not Modified
115
    if (validationSucceeded && m_cacheEntry)
115
    if (validationSucceeded && m_cacheEntry)
Lines 120-136 void SpeculativeLoad::didReceiveResponse(ResourceResponse&& receivedResponse, Re a/Source/WebKit/NetworkProcess/cache/NetworkCacheSpeculativeLoad.cpp_sec3
120
    completionHandler(PolicyAction::Use);
120
    completionHandler(PolicyAction::Use);
121
}
121
}
122
122
123
void SpeculativeLoad::didReceiveBuffer(Ref<SharedBuffer>&& buffer, int reportedEncodedDataLength)
123
void SpeculativeLoad::didReceiveBuffer(Ref<FragmentedSharedBuffer>&& buffer, int reportedEncodedDataLength)
124
{
124
{
125
    ASSERT(!m_cacheEntry);
125
    ASSERT(!m_cacheEntry);
126
126
127
    if (m_bufferedDataForCache) {
127
    if (m_bufferedDataForCache) {
128
        // Prevent memory growth in case of streaming data.
128
        // Prevent memory growth in case of streaming data.
129
        const size_t maximumCacheBufferSize = 10 * 1024 * 1024;
129
        const size_t maximumCacheBufferSize = 10 * 1024 * 1024;
130
        if (m_bufferedDataForCache->size() + buffer->size() <= maximumCacheBufferSize)
130
        if (m_bufferedDataForCache.size() + buffer->size() <= maximumCacheBufferSize)
131
            m_bufferedDataForCache->append(buffer.get());
131
            m_bufferedDataForCache.append(buffer.get());
132
        else
132
        else
133
            m_bufferedDataForCache = nullptr;
133
            m_bufferedDataForCache.reset();
134
    }
134
    }
135
}
135
}
136
136
Lines 139-148 void SpeculativeLoad::didFinishLoading(const WebCore::NetworkLoadMetrics&) a/Source/WebKit/NetworkProcess/cache/NetworkCacheSpeculativeLoad.cpp_sec4
139
    if (m_didComplete)
139
    if (m_didComplete)
140
        return;
140
        return;
141
    if (!m_cacheEntry && m_bufferedDataForCache) {
141
    if (!m_cacheEntry && m_bufferedDataForCache) {
142
        m_cacheEntry = m_cache->store(m_originalRequest, m_response, m_bufferedDataForCache.copyRef(), [](auto& mappedBody) { });
142
        m_cacheEntry = m_cache->store(m_originalRequest, m_response, m_bufferedDataForCache.get(), [](auto& mappedBody) { });
143
        // Create a synthetic cache entry if we can't store.
143
        // Create a synthetic cache entry if we can't store.
144
        if (!m_cacheEntry && isStatusCodeCacheableByDefault(m_response.httpStatusCode()))
144
        if (!m_cacheEntry && isStatusCodeCacheableByDefault(m_response.httpStatusCode()))
145
            m_cacheEntry = m_cache->makeEntry(m_originalRequest, m_response, WTFMove(m_bufferedDataForCache));
145
            m_cacheEntry = m_cache->makeEntry(m_originalRequest, m_response, m_bufferedDataForCache.take());
146
    }
146
    }
147
147
148
    didComplete();
148
    didComplete();
- a/Source/WebKit/NetworkProcess/cache/NetworkCacheSpeculativeLoad.h -2 / +2 lines
Lines 61-67 private: a/Source/WebKit/NetworkProcess/cache/NetworkCacheSpeculativeLoad.h_sec1
61
    bool isAllowedToAskUserForCredentials() const final { return false; }
61
    bool isAllowedToAskUserForCredentials() const final { return false; }
62
    void willSendRedirectedRequest(WebCore::ResourceRequest&&, WebCore::ResourceRequest&& redirectRequest, WebCore::ResourceResponse&& redirectResponse) override;
62
    void willSendRedirectedRequest(WebCore::ResourceRequest&&, WebCore::ResourceRequest&& redirectRequest, WebCore::ResourceResponse&& redirectResponse) override;
63
    void didReceiveResponse(WebCore::ResourceResponse&&, ResponseCompletionHandler&&) override;
63
    void didReceiveResponse(WebCore::ResourceResponse&&, ResponseCompletionHandler&&) override;
64
    void didReceiveBuffer(Ref<WebCore::SharedBuffer>&&, int reportedEncodedDataLength) override;
64
    void didReceiveBuffer(Ref<WebCore::FragmentedSharedBuffer>&&, int reportedEncodedDataLength) override;
65
    void didFinishLoading(const WebCore::NetworkLoadMetrics&) override;
65
    void didFinishLoading(const WebCore::NetworkLoadMetrics&) override;
66
    void didFailLoading(const WebCore::ResourceError&) override;
66
    void didFailLoading(const WebCore::ResourceError&) override;
67
67
Lines 75-81 private: a/Source/WebKit/NetworkProcess/cache/NetworkCacheSpeculativeLoad.h_sec2
75
75
76
    WebCore::ResourceResponse m_response;
76
    WebCore::ResourceResponse m_response;
77
77
78
    RefPtr<WebCore::SharedBuffer> m_bufferedDataForCache;
78
    WebCore::SharedBufferBuilder m_bufferedDataForCache;
79
    std::unique_ptr<NetworkCache::Entry> m_cacheEntry;
79
    std::unique_ptr<NetworkCache::Entry> m_cacheEntry;
80
    bool m_didComplete { false };
80
    bool m_didComplete { false };
81
};
81
};
- a/Source/WebKit/NetworkProcess/cache/PrefetchCache.cpp -2 / +2 lines
Lines 30-36 a/Source/WebKit/NetworkProcess/cache/PrefetchCache.cpp_sec1
30
30
31
namespace WebKit {
31
namespace WebKit {
32
32
33
PrefetchCache::Entry::Entry(WebCore::ResourceResponse&& response, RefPtr<WebCore::SharedBuffer>&& buffer)
33
PrefetchCache::Entry::Entry(WebCore::ResourceResponse&& response, RefPtr<WebCore::FragmentedSharedBuffer>&& buffer)
34
    : response(WTFMove(response)), buffer(WTFMove(buffer))
34
    : response(WTFMove(response)), buffer(WTFMove(buffer))
35
{
35
{
36
}
36
}
Lines 72-78 std::unique_ptr<PrefetchCache::Entry> PrefetchCache::take(const URL& url) a/Source/WebKit/NetworkProcess/cache/PrefetchCache.cpp_sec2
72
72
73
static const Seconds expirationTimeout { 5_s };
73
static const Seconds expirationTimeout { 5_s };
74
74
75
void PrefetchCache::store(const URL& requestUrl, WebCore::ResourceResponse&& response, RefPtr<WebCore::SharedBuffer>&& buffer)
75
void PrefetchCache::store(const URL& requestUrl, WebCore::ResourceResponse&& response, RefPtr<WebCore::FragmentedSharedBuffer>&& buffer)
76
{
76
{
77
    if (!m_sessionPrefetches)
77
    if (!m_sessionPrefetches)
78
        m_sessionPrefetches = makeUnique<PrefetchEntriesMap>();
78
        m_sessionPrefetches = makeUnique<PrefetchEntriesMap>();
- a/Source/WebKit/NetworkProcess/cache/PrefetchCache.h -4 / +4 lines
Lines 47-64 public: a/Source/WebKit/NetworkProcess/cache/PrefetchCache.h_sec1
47
47
48
    struct Entry {
48
    struct Entry {
49
        WTF_MAKE_STRUCT_FAST_ALLOCATED;
49
        WTF_MAKE_STRUCT_FAST_ALLOCATED;
50
        Entry(WebCore::ResourceResponse&&, RefPtr<WebCore::SharedBuffer>&&);
50
        Entry(WebCore::ResourceResponse&&, RefPtr<WebCore::FragmentedSharedBuffer>&&);
51
        Entry(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&);
51
        Entry(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&);
52
52
53
        Ref<WebCore::SharedBuffer> releaseBuffer() { return buffer.releaseNonNull(); }
53
        Ref<WebCore::FragmentedSharedBuffer> releaseBuffer() { return buffer.releaseNonNull(); }
54
54
55
        WebCore::ResourceResponse response;
55
        WebCore::ResourceResponse response;
56
        RefPtr<WebCore::SharedBuffer> buffer;
56
        RefPtr<WebCore::FragmentedSharedBuffer> buffer;
57
        WebCore::ResourceRequest redirectRequest;
57
        WebCore::ResourceRequest redirectRequest;
58
    };
58
    };
59
59
60
    std::unique_ptr<Entry> take(const URL&);
60
    std::unique_ptr<Entry> take(const URL&);
61
    void store(const URL&, WebCore::ResourceResponse&&, RefPtr<WebCore::SharedBuffer>&&);
61
    void store(const URL&, WebCore::ResourceResponse&&, RefPtr<WebCore::FragmentedSharedBuffer>&&);
62
    void storeRedirect(const URL&, WebCore::ResourceResponse&&, WebCore::ResourceRequest&&);
62
    void storeRedirect(const URL&, WebCore::ResourceResponse&&, WebCore::ResourceRequest&&);
63
63
64
private:
64
private:
- a/Source/WebKit/NetworkProcess/cocoa/NetworkDataTaskCocoa.h -1 / +1 lines
Lines 62-68 public: a/Source/WebKit/NetworkProcess/cocoa/NetworkDataTaskCocoa.h_sec1
62
    void didNegotiateModernTLS(const URL&);
62
    void didNegotiateModernTLS(const URL&);
63
    void didCompleteWithError(const WebCore::ResourceError&, const WebCore::NetworkLoadMetrics&);
63
    void didCompleteWithError(const WebCore::ResourceError&, const WebCore::NetworkLoadMetrics&);
64
    void didReceiveResponse(WebCore::ResourceResponse&&, NegotiatedLegacyTLS, ResponseCompletionHandler&&);
64
    void didReceiveResponse(WebCore::ResourceResponse&&, NegotiatedLegacyTLS, ResponseCompletionHandler&&);
65
    void didReceiveData(Ref<WebCore::SharedBuffer>&&);
65
    void didReceiveData(Ref<WebCore::FragmentedSharedBuffer>&&);
66
66
67
    void willPerformHTTPRedirection(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&, RedirectCompletionHandler&&);
67
    void willPerformHTTPRedirection(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&, RedirectCompletionHandler&&);
68
    void transferSandboxExtensionToDownload(Download&);
68
    void transferSandboxExtensionToDownload(Download&);
- a/Source/WebKit/NetworkProcess/cocoa/NetworkDataTaskCocoa.mm -1 / +1 lines
Lines 442-448 void NetworkDataTaskCocoa::didCompleteWithError(const WebCore::ResourceError& er a/Source/WebKit/NetworkProcess/cocoa/NetworkDataTaskCocoa.mm_sec1
442
        m_client->didCompleteWithError(error, networkLoadMetrics);
442
        m_client->didCompleteWithError(error, networkLoadMetrics);
443
}
443
}
444
444
445
void NetworkDataTaskCocoa::didReceiveData(Ref<WebCore::SharedBuffer>&& data)
445
void NetworkDataTaskCocoa::didReceiveData(Ref<WebCore::FragmentedSharedBuffer>&& data)
446
{
446
{
447
    WTFEmitSignpost(m_task.get(), "DataTask", "received %zd bytes", data->size());
447
    WTFEmitSignpost(m_task.get(), "DataTask", "received %zd bytes", data->size());
448
448
- a/Source/WebKit/NetworkProcess/curl/NetworkDataTaskCurl.cpp -1 / +1 lines
Lines 172-178 void NetworkDataTaskCurl::curlDidReceiveResponse(CurlRequest& request, CurlRespo a/Source/WebKit/NetworkProcess/curl/NetworkDataTaskCurl.cpp_sec1
172
    invokeDidReceiveResponse();
172
    invokeDidReceiveResponse();
173
}
173
}
174
174
175
void NetworkDataTaskCurl::curlDidReceiveBuffer(CurlRequest&, Ref<SharedBuffer>&& buffer)
175
void NetworkDataTaskCurl::curlDidReceiveBuffer(CurlRequest&, Ref<FragmentedSharedBuffer>&& buffer)
176
{
176
{
177
    Ref protectedThis { *this };
177
    Ref protectedThis { *this };
178
    if (state() == State::Canceling || state() == State::Completed || (!m_client && !isDownload()))
178
    if (state() == State::Canceling || state() == State::Completed || (!m_client && !isDownload()))
- a/Source/WebKit/NetworkProcess/curl/NetworkDataTaskCurl.h -1 / +1 lines
Lines 68-74 private: a/Source/WebKit/NetworkProcess/curl/NetworkDataTaskCurl.h_sec1
68
    Ref<WebCore::CurlRequest> createCurlRequest(WebCore::ResourceRequest&&, RequestStatus = RequestStatus::NewRequest);
68
    Ref<WebCore::CurlRequest> createCurlRequest(WebCore::ResourceRequest&&, RequestStatus = RequestStatus::NewRequest);
69
    void curlDidSendData(WebCore::CurlRequest&, unsigned long long, unsigned long long) override;
69
    void curlDidSendData(WebCore::CurlRequest&, unsigned long long, unsigned long long) override;
70
    void curlDidReceiveResponse(WebCore::CurlRequest&, WebCore::CurlResponse&&) override;
70
    void curlDidReceiveResponse(WebCore::CurlRequest&, WebCore::CurlResponse&&) override;
71
    void curlDidReceiveBuffer(WebCore::CurlRequest&, Ref<WebCore::SharedBuffer>&&) override;
71
    void curlDidReceiveBuffer(WebCore::CurlRequest&, Ref<WebCore::FragmentedSharedBuffer>&&) override;
72
    void curlDidComplete(WebCore::CurlRequest&, WebCore::NetworkLoadMetrics&&) override;
72
    void curlDidComplete(WebCore::CurlRequest&, WebCore::NetworkLoadMetrics&&) override;
73
    void curlDidFailWithError(WebCore::CurlRequest&, WebCore::ResourceError&&, WebCore::CertificateInfo&&) override;
73
    void curlDidFailWithError(WebCore::CurlRequest&, WebCore::ResourceError&&, WebCore::CertificateInfo&&) override;
74
74
- a/Source/WebKit/NetworkProcess/webrtc/NetworkRTCProvider.h -1 / +1 lines
Lines 55-61 struct PacketOptions; a/Source/WebKit/NetworkProcess/webrtc/NetworkRTCProvider.h_sec1
55
55
56
namespace WebCore {
56
namespace WebCore {
57
class RegistrableDomain;
57
class RegistrableDomain;
58
class SharedBuffer;
58
class FragmentedSharedBuffer;
59
}
59
}
60
60
61
namespace WebKit {
61
namespace WebKit {
- a/Source/WebKit/Platform/IPC/SharedBufferCopy.h -6 / +7 lines
Lines 23-29 a/Source/WebKit/Platform/IPC/SharedBufferCopy.h_sec1
23
 * THE POSSIBILITY OF SUCH DAMAGE.
23
 * THE POSSIBILITY OF SUCH DAMAGE.
24
 */
24
 */
25
25
26
// Encodes a SharedBuffer that is received as a copy of the decoded data in a new SharedBuffer.
26
// Encodes a FragmentedSharedBuffer that is received as a copy of the decoded data in a new FragmentedSharedBuffer.
27
// To avoid copying from the Decoder, use SharedBufferDataReference to receive a DataReference instead.
27
// To avoid copying from the Decoder, use SharedBufferDataReference to receive a DataReference instead.
28
28
29
#pragma once
29
#pragma once
Lines 43-53 public: a/Source/WebKit/Platform/IPC/SharedBufferCopy.h_sec2
43
        : m_buffer(WTFMove(buffer)) { }
43
        : m_buffer(WTFMove(buffer)) { }
44
    SharedBufferCopy(Ref<WebCore::SharedBuffer>&& buffer)
44
    SharedBufferCopy(Ref<WebCore::SharedBuffer>&& buffer)
45
        : m_buffer(WTFMove(buffer)) { }
45
        : m_buffer(WTFMove(buffer)) { }
46
    SharedBufferCopy(const WebCore::SharedBuffer& buffer)
46
    SharedBufferCopy(RefPtr<WebCore::FragmentedSharedBuffer>&& buffer)
47
        : m_buffer(WebCore::SharedBuffer::create())
47
        : m_buffer(buffer ? buffer->makeContiguous() : RefPtr<WebCore::SharedBuffer>()) { }
48
    {
48
    SharedBufferCopy(Ref<WebCore::FragmentedSharedBuffer>&& buffer)
49
        m_buffer->append(buffer);
49
        : m_buffer(buffer->makeContiguous()) { }
50
    }
50
    SharedBufferCopy(const WebCore::FragmentedSharedBuffer& buffer)
51
        : m_buffer(buffer.makeContiguous()) { }
51
52
52
    RefPtr<WebCore::SharedBuffer>& buffer() { return m_buffer; }
53
    RefPtr<WebCore::SharedBuffer>& buffer() { return m_buffer; }
53
    const RefPtr<WebCore::SharedBuffer>& buffer() const { return m_buffer; }
54
    const RefPtr<WebCore::SharedBuffer>& buffer() const { return m_buffer; }
- a/Source/WebKit/Platform/IPC/SharedBufferDataReference.h -1 / +1 lines
Lines 23-29 a/Source/WebKit/Platform/IPC/SharedBufferDataReference.h_sec1
23
 * THE POSSIBILITY OF SUCH DAMAGE.
23
 * THE POSSIBILITY OF SUCH DAMAGE.
24
 */
24
 */
25
25
26
// Encodes a SharedBuffer or DataReference that is received as a DataReference to the decoded data.
26
// Encodes a FragmentedSharedBuffer or DataReference that is received as a DataReference to the decoded data.
27
27
28
#pragma once
28
#pragma once
29
29
- a/Source/WebKit/Platform/SharedMemory.cpp -2 / +2 lines
Lines 32-38 namespace WebKit { a/Source/WebKit/Platform/SharedMemory.cpp_sec1
32
32
33
using namespace WebCore;
33
using namespace WebCore;
34
34
35
RefPtr<SharedMemory> SharedMemory::copyBuffer(const SharedBuffer& buffer)
35
RefPtr<SharedMemory> SharedMemory::copyBuffer(const FragmentedSharedBuffer& buffer)
36
{
36
{
37
    if (buffer.isEmpty())
37
    if (buffer.isEmpty())
38
        return nullptr;
38
        return nullptr;
Lines 51-57 RefPtr<SharedMemory> SharedMemory::copyBuffer(const SharedBuffer& buffer) a/Source/WebKit/Platform/SharedMemory.cpp_sec2
51
Ref<SharedBuffer> SharedMemory::createSharedBuffer(size_t dataSize) const
51
Ref<SharedBuffer> SharedMemory::createSharedBuffer(size_t dataSize) const
52
{
52
{
53
    ASSERT(dataSize <= size());
53
    ASSERT(dataSize <= size());
54
    return SharedBuffer::create({
54
    return SharedBuffer::create(DataSegment::Provider {
55
        [protectedThis = Ref { *this }] () -> const uint8_t* {
55
        [protectedThis = Ref { *this }] () -> const uint8_t* {
56
            return static_cast<const uint8_t*>(protectedThis->data());
56
            return static_cast<const uint8_t*>(protectedThis->data());
57
        },
57
        },
- a/Source/WebKit/Platform/SharedMemory.h -1 / +2 lines
Lines 45-50 class Encoder; a/Source/WebKit/Platform/SharedMemory.h_sec1
45
45
46
namespace WebCore {
46
namespace WebCore {
47
class SharedBuffer;
47
class SharedBuffer;
48
class FragmentedSharedBuffer;
48
}
49
}
49
50
50
#if OS(DARWIN)
51
#if OS(DARWIN)
Lines 120-126 public: a/Source/WebKit/Platform/SharedMemory.h_sec2
120
121
121
    // FIXME: Change these factory functions to return Ref<SharedMemory> and crash on failure.
122
    // FIXME: Change these factory functions to return Ref<SharedMemory> and crash on failure.
122
    static RefPtr<SharedMemory> allocate(size_t);
123
    static RefPtr<SharedMemory> allocate(size_t);
123
    static RefPtr<SharedMemory> copyBuffer(const WebCore::SharedBuffer&);
124
    static RefPtr<SharedMemory> copyBuffer(const WebCore::FragmentedSharedBuffer&);
124
    static RefPtr<SharedMemory> map(const Handle&, Protection);
125
    static RefPtr<SharedMemory> map(const Handle&, Protection);
125
#if USE(UNIX_DOMAIN_SOCKETS)
126
#if USE(UNIX_DOMAIN_SOCKETS)
126
    static RefPtr<SharedMemory> wrapMap(void*, size_t, int fileDescriptor);
127
    static RefPtr<SharedMemory> wrapMap(void*, size_t, int fileDescriptor);
- a/Source/WebKit/Shared/APIWebArchiveResource.mm -1 / +1 lines
Lines 68-74 static void releaseWebArchiveResourceData(unsigned char*, const void* data) a/Source/WebKit/Shared/APIWebArchiveResource.mm_sec1
68
68
69
Ref<API::Data> WebArchiveResource::data()
69
Ref<API::Data> WebArchiveResource::data()
70
{
70
{
71
    RetainPtr<CFDataRef> cfData = m_archiveResource->data().createCFData();
71
    RetainPtr<CFDataRef> cfData = m_archiveResource->data().makeContiguous()->createCFData();
72
72
73
    // Balanced by CFRelease in releaseWebArchiveResourceData.
73
    // Balanced by CFRelease in releaseWebArchiveResourceData.
74
    CFRetain(cfData.get());
74
    CFRetain(cfData.get());
- a/Source/WebKit/Shared/Cocoa/WebCoreArgumentCodersCocoa.mm -3 / +2 lines
Lines 564-576 std::optional<WebCore::FontPlatformData> ArgumentCoder<Ref<WebCore::Font>>::deco a/Source/WebKit/Shared/Cocoa/WebCoreArgumentCodersCocoa.mm_sec1
564
        return std::nullopt;
564
        return std::nullopt;
565
565
566
    if (*includesCreationData) {
566
    if (*includesCreationData) {
567
        std::optional<Ref<WebCore::SharedBuffer>> fontFaceData;
567
        std::optional<Ref<WebCore::FragmentedSharedBuffer>> fontFaceData;
568
        decoder >> fontFaceData;
568
        decoder >> fontFaceData;
569
        if (!fontFaceData)
569
        if (!fontFaceData)
570
            return std::nullopt;
570
            return std::nullopt;
571
571
572
        // Upon receipt, copy the data for security, so the sender can't scribble over it while we're using it.
572
        auto localFontFaceData = fontFaceData.value()->makeContiguous();
573
        auto localFontFaceData = WebCore::SharedBuffer::create(fontFaceData.value()->data(), fontFaceData.value()->size());
574
573
575
        std::optional<String> itemInCollection;
574
        std::optional<String> itemInCollection;
576
        decoder >> itemInCollection;
575
        decoder >> itemInCollection;
- a/Source/WebKit/Shared/ShareableResource.cpp -1 / +1 lines
Lines 57-63 bool ShareableResource::Handle::decode(IPC::Decoder& decoder, Handle& handle) a/Source/WebKit/Shared/ShareableResource.cpp_sec1
57
57
58
RefPtr<SharedBuffer> ShareableResource::wrapInSharedBuffer()
58
RefPtr<SharedBuffer> ShareableResource::wrapInSharedBuffer()
59
{
59
{
60
    return SharedBuffer::create(SharedBuffer::DataSegment::Provider {
60
    return SharedBuffer::create(DataSegment::Provider {
61
        [self = Ref { *this }]() { return self->data(); },
61
        [self = Ref { *this }]() { return self->data(); },
62
        [self = Ref { *this }]() { return self->size(); }
62
        [self = Ref { *this }]() { return self->size(); }
63
    });
63
    });
- a/Source/WebKit/Shared/WebCoreArgumentCoders.cpp -8 / +36 lines
Lines 164-170 DEFINE_SIMPLE_ARGUMENT_CODER_FOR_SOURCE(DisplayList::SetInlineStrokeColor) a/Source/WebKit/Shared/WebCoreArgumentCoders.cpp_sec1
164
164
165
#undef DEFINE_SIMPLE_ARGUMENT_CODER_FOR_SOURCE
165
#undef DEFINE_SIMPLE_ARGUMENT_CODER_FOR_SOURCE
166
166
167
static void encodeSharedBuffer(Encoder& encoder, const SharedBuffer* buffer)
167
static void encodeSharedBuffer(Encoder& encoder, const FragmentedSharedBuffer* buffer)
168
{
168
{
169
    bool isNull = !buffer;
169
    bool isNull = !buffer;
170
    encoder << isNull;
170
    encoder << isNull;
Lines 177-183 static void encodeSharedBuffer(Encoder& encoder, const SharedBuffer* buffer) a/Source/WebKit/Shared/WebCoreArgumentCoders.cpp_sec2
177
        return;
177
        return;
178
178
179
#if USE(UNIX_DOMAIN_SOCKETS)
179
#if USE(UNIX_DOMAIN_SOCKETS)
180
    // Do not use shared memory for SharedBuffer encoding in Unix, because it's easy to reach the
180
    // Do not use shared memory for FragmentedSharedBuffer encoding in Unix, because it's easy to reach the
181
    // maximum number of file descriptors open per process when sending large data in small chunks
181
    // maximum number of file descriptors open per process when sending large data in small chunks
182
    // over the IPC. ConnectionUnix.cpp already uses shared memory to send any IPC message that is
182
    // over the IPC. ConnectionUnix.cpp already uses shared memory to send any IPC message that is
183
    // too large. See https://bugs.webkit.org/show_bug.cgi?id=208571.
183
    // too large. See https://bugs.webkit.org/show_bug.cgi?id=208571.
Lines 264-270 static WARN_UNUSED_RETURN bool decodeTypesAndData(Decoder& decoder, Vector<Strin a/Source/WebKit/Shared/WebCoreArgumentCoders.cpp_sec3
264
        RefPtr<SharedBuffer> buffer;
264
        RefPtr<SharedBuffer> buffer;
265
        if (!decodeSharedBuffer(decoder, buffer))
265
        if (!decodeSharedBuffer(decoder, buffer))
266
            return false;
266
            return false;
267
        data.append(WTFMove(buffer));
267
        data.append(buffer);
268
    }
268
    }
269
269
270
    return true;
270
    return true;
Lines 1550-1559 void ArgumentCoder<PasteboardCustomData::Entry>::encode(Encoder& encoder, const a/Source/WebKit/Shared/WebCoreArgumentCoders.cpp_sec4
1550
    if (hasString)
1550
    if (hasString)
1551
        encoder << std::get<String>(platformData);
1551
        encoder << std::get<String>(platformData);
1552
1552
1553
    bool hasBuffer = std::holds_alternative<Ref<SharedBuffer>>(platformData);
1553
    bool hasBuffer = std::holds_alternative<Ref<FragmentedSharedBuffer>>(platformData);
1554
    encoder << hasBuffer;
1554
    encoder << hasBuffer;
1555
    if (hasBuffer)
1555
    if (hasBuffer)
1556
        encodeSharedBuffer(encoder, std::get<Ref<SharedBuffer>>(platformData).ptr());
1556
        encodeSharedBuffer(encoder, std::get<Ref<FragmentedSharedBuffer>>(platformData).ptr());
1557
}
1557
}
1558
1558
1559
bool ArgumentCoder<PasteboardCustomData::Entry>::decode(Decoder& decoder, PasteboardCustomData::Entry& data)
1559
bool ArgumentCoder<PasteboardCustomData::Entry>::decode(Decoder& decoder, PasteboardCustomData::Entry& data)
Lines 2976-2982 std::optional<SerializedAttachmentData> ArgumentCoder<WebCore::SerializedAttachm a/Source/WebKit/Shared/WebCoreArgumentCoders.cpp_sec5
2976
    if (!decoder.decode(data))
2976
    if (!decoder.decode(data))
2977
        return std::nullopt;
2977
        return std::nullopt;
2978
2978
2979
    return {{ WTFMove(identifier), WTFMove(mimeType), WebCore::SharedBuffer::create(data.data(), data.size()) }};
2979
    return { { WTFMove(identifier), WTFMove(mimeType), WebCore::SharedBuffer::create(data.data(), data.size()) } };
2980
}
2980
}
2981
2981
2982
#endif // ENABLE(ATTACHMENT_ELEMENT)
2982
#endif // ENABLE(ATTACHMENT_ELEMENT)
Lines 3010-3015 std::optional<SerializedPlatformDataCueValue> ArgumentCoder<WebCore::SerializedP a/Source/WebKit/Shared/WebCoreArgumentCoders.cpp_sec6
3010
}
3010
}
3011
#endif
3011
#endif
3012
3012
3013
void ArgumentCoder<RefPtr<WebCore::FragmentedSharedBuffer>>::encode(Encoder& encoder, const RefPtr<WebCore::FragmentedSharedBuffer>& buffer)
3014
{
3015
    encodeSharedBuffer(encoder, buffer.get());
3016
}
3017
3018
std::optional<RefPtr<FragmentedSharedBuffer>> ArgumentCoder<RefPtr<WebCore::FragmentedSharedBuffer>>::decode(Decoder& decoder)
3019
{
3020
    RefPtr<SharedBuffer> buffer;
3021
    if (!decodeSharedBuffer(decoder, buffer))
3022
        return std::nullopt;
3023
3024
    return buffer;
3025
}
3026
3027
void ArgumentCoder<Ref<WebCore::FragmentedSharedBuffer>>::encode(Encoder& encoder, const Ref<WebCore::FragmentedSharedBuffer>& buffer)
3028
{
3029
    encodeSharedBuffer(encoder, buffer.ptr());
3030
}
3031
3032
std::optional<Ref<FragmentedSharedBuffer>> ArgumentCoder<Ref<WebCore::FragmentedSharedBuffer>>::decode(Decoder& decoder)
3033
{
3034
    RefPtr<SharedBuffer> buffer;
3035
    if (!decodeSharedBuffer(decoder, buffer) || !buffer)
3036
        return std::nullopt;
3037
3038
    return buffer.releaseNonNull();
3039
}
3040
3013
void ArgumentCoder<RefPtr<WebCore::SharedBuffer>>::encode(Encoder& encoder, const RefPtr<WebCore::SharedBuffer>& buffer)
3041
void ArgumentCoder<RefPtr<WebCore::SharedBuffer>>::encode(Encoder& encoder, const RefPtr<WebCore::SharedBuffer>& buffer)
3014
{
3042
{
3015
    encodeSharedBuffer(encoder, buffer.get());
3043
    encodeSharedBuffer(encoder, buffer.get());
Lines 3107-3113 void ArgumentCoder<WebCore::CDMInstanceSession::Message>::encode(Encoder& encode a/Source/WebKit/Shared/WebCoreArgumentCoders.cpp_sec7
3107
{
3135
{
3108
    encoder << message.first;
3136
    encoder << message.first;
3109
3137
3110
    RefPtr<SharedBuffer> messageData = message.second.copyRef();
3138
    RefPtr<FragmentedSharedBuffer> messageData = message.second.copyRef();
3111
    encoder << messageData;
3139
    encoder << messageData;
3112
}
3140
}
3113
3141
Lines 3117-3123 std::optional<WebCore::CDMInstanceSession::Message> ArgumentCoder<WebCore::CDMI a/Source/WebKit/Shared/WebCoreArgumentCoders.cpp_sec8
3117
    if (!decoder.decode(type))
3145
    if (!decoder.decode(type))
3118
        return std::nullopt;
3146
        return std::nullopt;
3119
3147
3120
    RefPtr<SharedBuffer> buffer;
3148
    RefPtr<FragmentedSharedBuffer> buffer;
3121
    if (!decoder.decode(buffer) || !buffer)
3149
    if (!decoder.decode(buffer) || !buffer)
3122
        return std::nullopt;
3150
        return std::nullopt;
3123
3151
- a/Source/WebKit/Shared/WebCoreArgumentCoders.h -1 / +12 lines
Lines 114-119 class AuthenticationChallenge; a/Source/WebKit/Shared/WebCoreArgumentCoders.h_sec1
114
class BlobPart;
114
class BlobPart;
115
class CertificateInfo;
115
class CertificateInfo;
116
class Color;
116
class Color;
117
class SharedBuffer;
117
class Credential;
118
class Credential;
118
class CubicBezierTimingFunction;
119
class CubicBezierTimingFunction;
119
class Cursor;
120
class Cursor;
Lines 138-144 class ResourceRequest; a/Source/WebKit/Shared/WebCoreArgumentCoders.h_sec2
138
class ResourceResponse;
139
class ResourceResponse;
139
class ScriptBuffer;
140
class ScriptBuffer;
140
class SecurityOrigin;
141
class SecurityOrigin;
141
class SharedBuffer;
142
class FragmentedSharedBuffer;
142
class SpringTimingFunction;
143
class SpringTimingFunction;
143
class StepsTimingFunction;
144
class StepsTimingFunction;
144
class StickyPositionViewportConstraints;
145
class StickyPositionViewportConstraints;
Lines 751-756 template<> struct ArgumentCoder<WebCore::SerializedPlatformDataCueValue> { a/Source/WebKit/Shared/WebCoreArgumentCoders.h_sec3
751
};
752
};
752
#endif
753
#endif
753
754
755
template<> struct ArgumentCoder<RefPtr<WebCore::FragmentedSharedBuffer>> {
756
    static void encode(Encoder&, const RefPtr<WebCore::FragmentedSharedBuffer>&);
757
    static std::optional<RefPtr<WebCore::FragmentedSharedBuffer>> decode(Decoder&);
758
};
759
760
template<> struct ArgumentCoder<Ref<WebCore::FragmentedSharedBuffer>> {
761
    static void encode(Encoder&, const Ref<WebCore::FragmentedSharedBuffer>&);
762
    static std::optional<Ref<WebCore::FragmentedSharedBuffer>> decode(Decoder&);
763
};
764
754
template<> struct ArgumentCoder<RefPtr<WebCore::SharedBuffer>> {
765
template<> struct ArgumentCoder<RefPtr<WebCore::SharedBuffer>> {
755
    static void encode(Encoder&, const RefPtr<WebCore::SharedBuffer>&);
766
    static void encode(Encoder&, const RefPtr<WebCore::SharedBuffer>&);
756
    static std::optional<RefPtr<WebCore::SharedBuffer>> decode(Decoder&);
767
    static std::optional<RefPtr<WebCore::SharedBuffer>> decode(Decoder&);
- a/Source/WebKit/Shared/WebHitTestResultData.cpp -1 / +1 lines
Lines 85-91 WebHitTestResultData::WebHitTestResultData(const WebCore::HitTestResult& hitTest a/Source/WebKit/Shared/WebHitTestResultData.cpp_sec1
85
        return;
85
        return;
86
86
87
    if (Image* image = hitTestResult.image()) {
87
    if (Image* image = hitTestResult.image()) {
88
        RefPtr<SharedBuffer> buffer = image->data();
88
        RefPtr<FragmentedSharedBuffer> buffer = image->data();
89
        if (buffer) {
89
        if (buffer) {
90
            imageSharedMemory = WebKit::SharedMemory::copyBuffer(*buffer);
90
            imageSharedMemory = WebKit::SharedMemory::copyBuffer(*buffer);
91
            imageSize = buffer->size();
91
            imageSize = buffer->size();
- a/Source/WebKit/Shared/gtk/ArgumentCodersGtk.cpp -1 / +1 lines
Lines 95-101 void ArgumentCoder<SelectionData>::encode(Encoder& encoder, const SelectionData& a/Source/WebKit/Shared/gtk/ArgumentCodersGtk.cpp_sec1
95
    bool hasCustomData = selection.hasCustomData();
95
    bool hasCustomData = selection.hasCustomData();
96
    encoder << hasCustomData;
96
    encoder << hasCustomData;
97
    if (hasCustomData)
97
    if (hasCustomData)
98
        encoder << RefPtr<SharedBuffer>(selection.customData());
98
        encoder << RefPtr<FragmentedSharedBuffer>(selection.customData());
99
99
100
    bool canSmartReplace = selection.canSmartReplace();
100
    bool canSmartReplace = selection.canSmartReplace();
101
    encoder << canSmartReplace;
101
    encoder << canSmartReplace;
- a/Source/WebKit/UIProcess/API/APIAttachment.cpp -1 / +1 lines
Lines 98-104 std::optional<uint64_t> Attachment::fileSizeForDisplay() const a/Source/WebKit/UIProcess/API/APIAttachment.cpp_sec1
98
    return std::nullopt;
98
    return std::nullopt;
99
}
99
}
100
100
101
RefPtr<WebCore::SharedBuffer> Attachment::enclosingImageData() const
101
RefPtr<WebCore::FragmentedSharedBuffer> Attachment::enclosingImageData() const
102
{
102
{
103
    return nullptr;
103
    return nullptr;
104
}
104
}
- a/Source/WebKit/UIProcess/API/APIAttachment.h -1 / +2 lines
Lines 39-44 OBJC_CLASS NSString; a/Source/WebKit/UIProcess/API/APIAttachment.h_sec1
39
39
40
namespace WebCore {
40
namespace WebCore {
41
class SharedBuffer;
41
class SharedBuffer;
42
class FragmentedSharedBuffer;
42
}
43
}
43
44
44
namespace WebKit {
45
namespace WebKit {
Lines 82-88 public: a/Source/WebKit/UIProcess/API/APIAttachment.h_sec2
82
83
83
    bool isEmpty() const;
84
    bool isEmpty() const;
84
85
85
    RefPtr<WebCore::SharedBuffer> enclosingImageData() const;
86
    RefPtr<WebCore::FragmentedSharedBuffer> enclosingImageData() const;
86
    std::optional<uint64_t> fileSizeForDisplay() const;
87
    std::optional<uint64_t> fileSizeForDisplay() const;
87
88
88
    void setHasEnclosingImage(bool hasEnclosingImage) { m_hasEnclosingImage = hasEnclosingImage; }
89
    void setHasEnclosingImage(bool hasEnclosingImage) { m_hasEnclosingImage = hasEnclosingImage; }
- a/Source/WebKit/UIProcess/API/APIContentRuleListStore.h -1 / +1 lines
Lines 30-36 a/Source/WebKit/UIProcess/API/APIContentRuleListStore.h_sec1
30
#include <wtf/text/WTFString.h>
30
#include <wtf/text/WTFString.h>
31
31
32
namespace WebCore {
32
namespace WebCore {
33
class SharedBuffer;
33
class FragmentedSharedBuffer;
34
}
34
}
35
35
36
namespace WTF {
36
namespace WTF {
- a/Source/WebKit/UIProcess/API/APINavigationClient.h -2 / +2 lines
Lines 47-53 struct ContentRuleListResults; a/Source/WebKit/UIProcess/API/APINavigationClient.h_sec1
47
class ResourceError;
47
class ResourceError;
48
class ResourceRequest;
48
class ResourceRequest;
49
class ResourceResponse;
49
class ResourceResponse;
50
class SharedBuffer;
50
class FragmentedSharedBuffer;
51
struct SecurityOriginData;
51
struct SecurityOriginData;
52
}
52
}
53
53
Lines 119-125 public: a/Source/WebKit/UIProcess/API/APINavigationClient.h_sec2
119
119
120
#if USE(QUICK_LOOK)
120
#if USE(QUICK_LOOK)
121
    virtual void didStartLoadForQuickLookDocumentInMainFrame(const WTF::String& fileName, const WTF::String& uti) { }
121
    virtual void didStartLoadForQuickLookDocumentInMainFrame(const WTF::String& fileName, const WTF::String& uti) { }
122
    virtual void didFinishLoadForQuickLookDocumentInMainFrame(const WebCore::SharedBuffer&) { }
122
    virtual void didFinishLoadForQuickLookDocumentInMainFrame(const WebCore::FragmentedSharedBuffer&) { }
123
#endif
123
#endif
124
124
125
    virtual void decidePolicyForNavigationAction(WebKit::WebPageProxy&, Ref<NavigationAction>&&, Ref<WebKit::WebFramePolicyListenerProxy>&& listener, Object*)
125
    virtual void decidePolicyForNavigationAction(WebKit::WebPageProxy&, Ref<NavigationAction>&&, Ref<WebKit::WebFramePolicyListenerProxy>&& listener, Object*)
- a/Source/WebKit/UIProcess/API/Cocoa/APIAttachmentCocoa.mm -1 / +1 lines
Lines 137-143 std::optional<uint64_t> Attachment::fileSizeForDisplay() const a/Source/WebKit/UIProcess/API/Cocoa/APIAttachmentCocoa.mm_sec1
137
    return [fileWrapper regularFileContents].length;
137
    return [fileWrapper regularFileContents].length;
138
}
138
}
139
139
140
RefPtr<WebCore::SharedBuffer> Attachment::enclosingImageData() const
140
RefPtr<WebCore::FragmentedSharedBuffer> Attachment::enclosingImageData() const
141
{
141
{
142
    if (!m_hasEnclosingImage)
142
    if (!m_hasEnclosingImage)
143
        return nullptr;
143
        return nullptr;
- a/Source/WebKit/UIProcess/API/Cocoa/WKWebView.mm -1 / +1 lines
Lines 1596-1602 - (void)_storeAppHighlight:(const WebCore::AppHighlight&)highlight a/Source/WebKit/UIProcess/API/Cocoa/WKWebView.mm_sec1
1596
    if (highlight.text)
1596
    if (highlight.text)
1597
        text = highlight.text.value();
1597
        text = highlight.text.value();
1598
1598
1599
    auto wkHighlight = adoptNS([[_WKAppHighlight alloc] initWithHighlight:highlight.highlight->createNSData().get() text:text image:nil]);
1599
    auto wkHighlight = adoptNS([[_WKAppHighlight alloc] initWithHighlight:highlight.highlight->makeContiguous()->createNSData().get() text:text image:nil]);
1600
1600
1601
    if ([delegate respondsToSelector:@selector(_webView:storeAppHighlight:inNewGroup:requestOriginatedInApp:)])
1601
    if ([delegate respondsToSelector:@selector(_webView:storeAppHighlight:inNewGroup:requestOriginatedInApp:)])
1602
        [delegate _webView:self storeAppHighlight:wkHighlight.get() inNewGroup:highlight.isNewGroup == WebCore::CreateNewGroupForHighlight::Yes requestOriginatedInApp:highlight.requestOriginatedInApp == WebCore::HighlightRequestOriginatedInApp::Yes];
1602
        [delegate _webView:self storeAppHighlight:wkHighlight.get() inNewGroup:highlight.isNewGroup == WebCore::CreateNewGroupForHighlight::Yes requestOriginatedInApp:highlight.requestOriginatedInApp == WebCore::HighlightRequestOriginatedInApp::Yes];
- a/Source/WebKit/UIProcess/Cocoa/NavigationState.h -1 / +1 lines
Lines 133-139 private: a/Source/WebKit/UIProcess/Cocoa/NavigationState.h_sec1
133
133
134
#if USE(QUICK_LOOK)
134
#if USE(QUICK_LOOK)
135
        void didStartLoadForQuickLookDocumentInMainFrame(const WTF::String& fileName, const WTF::String& uti) override;
135
        void didStartLoadForQuickLookDocumentInMainFrame(const WTF::String& fileName, const WTF::String& uti) override;
136
        void didFinishLoadForQuickLookDocumentInMainFrame(const WebCore::SharedBuffer&) override;
136
        void didFinishLoadForQuickLookDocumentInMainFrame(const WebCore::FragmentedSharedBuffer&) override;
137
#endif
137
#endif
138
138
139
#if PLATFORM(MAC)
139
#if PLATFORM(MAC)
- a/Source/WebKit/UIProcess/Cocoa/NavigationState.mm -2 / +2 lines
Lines 1220-1226 void NavigationState::NavigationClient::didStartLoadForQuickLookDocumentInMainFr a/Source/WebKit/UIProcess/Cocoa/NavigationState.mm_sec1
1220
    [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate.get()) _webView:m_navigationState->m_webView didStartLoadForQuickLookDocumentInMainFrameWithFileName:fileName uti:uti];
1220
    [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate.get()) _webView:m_navigationState->m_webView didStartLoadForQuickLookDocumentInMainFrameWithFileName:fileName uti:uti];
1221
}
1221
}
1222
1222
1223
void NavigationState::NavigationClient::didFinishLoadForQuickLookDocumentInMainFrame(const SharedBuffer& buffer)
1223
void NavigationState::NavigationClient::didFinishLoadForQuickLookDocumentInMainFrame(const FragmentedSharedBuffer& buffer)
1224
{
1224
{
1225
    if (!m_navigationState)
1225
    if (!m_navigationState)
1226
        return;
1226
        return;
Lines 1232-1238 void NavigationState::NavigationClient::didFinishLoadForQuickLookDocumentInMainF a/Source/WebKit/UIProcess/Cocoa/NavigationState.mm_sec2
1232
    if (!navigationDelegate)
1232
    if (!navigationDelegate)
1233
        return;
1233
        return;
1234
1234
1235
    [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate.get()) _webView:m_navigationState->m_webView didFinishLoadForQuickLookDocumentInMainFrame:buffer.createNSData().get()];
1235
    [static_cast<id <WKNavigationDelegatePrivate>>(navigationDelegate.get()) _webView:m_navigationState->m_webView didFinishLoadForQuickLookDocumentInMainFrame:buffer.makeContiguous()->createNSData().get()];
1236
}
1236
}
1237
#endif
1237
#endif
1238
1238
- a/Source/WebKit/UIProcess/Cocoa/WebProcessProxyCocoa.mm -2 / +2 lines
Lines 302-313 void WebProcessProxy::sendAudioComponentRegistrations() a/Source/WebKit/UIProcess/Cocoa/WebProcessProxyCocoa.mm_sec1
302
        if (noErr != AudioComponentFetchServerRegistrations(&registrations) || !registrations)
302
        if (noErr != AudioComponentFetchServerRegistrations(&registrations) || !registrations)
303
            return;
303
            return;
304
304
305
        RunLoop::main().dispatch([weakThis = WTFMove(weakThis), registrations = adoptCF(registrations)] () mutable {
305
        RunLoop::main().dispatch([weakThis = WTFMove(weakThis), registrations = adoptCF(registrations)] () {
306
            if (!weakThis)
306
            if (!weakThis)
307
                return;
307
                return;
308
308
309
            auto registrationData = WebCore::SharedBuffer::create(registrations.get());
309
            auto registrationData = WebCore::SharedBuffer::create(registrations.get());
310
            weakThis->send(Messages::WebProcess::ConsumeAudioComponentRegistrations({ registrationData }), 0);
310
            weakThis->send(Messages::WebProcess::ConsumeAudioComponentRegistrations({ WTFMove(registrationData) }), 0);
311
        });
311
        });
312
    });
312
    });
313
}
313
}
- a/Source/WebKit/UIProcess/Cocoa/WebViewImpl.h -1 / +1 lines
Lines 506-512 public: a/Source/WebKit/UIProcess/Cocoa/WebViewImpl.h_sec1
506
506
507
    void startDrag(const WebCore::DragItem&, const ShareableBitmap::Handle& image);
507
    void startDrag(const WebCore::DragItem&, const ShareableBitmap::Handle& image);
508
    void setFileAndURLTypes(NSString *filename, NSString *extension, NSString *title, NSString *url, NSString *visibleURL, NSPasteboard *);
508
    void setFileAndURLTypes(NSString *filename, NSString *extension, NSString *title, NSString *url, NSString *visibleURL, NSPasteboard *);
509
    void setPromisedDataForImage(WebCore::Image*, NSString *filename, NSString *extension, NSString *title, NSString *url, NSString *visibleURL, WebCore::SharedBuffer* archiveBuffer, NSString *pasteboardName, NSString *pasteboardOrigin);
509
    void setPromisedDataForImage(WebCore::Image*, NSString *filename, NSString *extension, NSString *title, NSString *url, NSString *visibleURL, WebCore::FragmentedSharedBuffer* archiveBuffer, NSString *pasteboardName, NSString *pasteboardOrigin);
510
    void pasteboardChangedOwner(NSPasteboard *);
510
    void pasteboardChangedOwner(NSPasteboard *);
511
    void provideDataForPasteboard(NSPasteboard *, NSString *type);
511
    void provideDataForPasteboard(NSPasteboard *, NSString *type);
512
    NSArray *namesOfPromisedFilesDroppedAtDestination(NSURL *dropDestination);
512
    NSArray *namesOfPromisedFilesDroppedAtDestination(NSURL *dropDestination);
- a/Source/WebKit/UIProcess/Cocoa/WebViewImpl.mm -4 / +4 lines
Lines 4449-4455 void WebViewImpl::setFileAndURLTypes(NSString *filename, NSString *extension, NS a/Source/WebKit/UIProcess/Cocoa/WebViewImpl.mm_sec1
4449
    m_promisedURL = url;
4449
    m_promisedURL = url;
4450
}
4450
}
4451
4451
4452
void WebViewImpl::setPromisedDataForImage(WebCore::Image* image, NSString *filename, NSString *extension, NSString *title, NSString *url, NSString *visibleURL, WebCore::SharedBuffer* archiveBuffer, NSString *pasteboardName, NSString *originIdentifier)
4452
void WebViewImpl::setPromisedDataForImage(WebCore::Image* image, NSString *filename, NSString *extension, NSString *title, NSString *url, NSString *visibleURL, WebCore::FragmentedSharedBuffer* archiveBuffer, NSString *pasteboardName, NSString *originIdentifier)
4453
{
4453
{
4454
    NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:pasteboardName];
4454
    NSPasteboard *pasteboard = [NSPasteboard pasteboardWithName:pasteboardName];
4455
    RetainPtr<NSMutableArray> types = adoptNS([[NSMutableArray alloc] initWithObjects:WebCore::legacyFilesPromisePasteboardType(), nil]);
4455
    RetainPtr<NSMutableArray> types = adoptNS([[NSMutableArray alloc] initWithObjects:WebCore::legacyFilesPromisePasteboardType(), nil]);
Lines 4470-4476 void WebViewImpl::setPromisedDataForImage(WebCore::Image* image, NSString *filen a/Source/WebKit/UIProcess/Cocoa/WebViewImpl.mm_sec2
4470
    setFileAndURLTypes(filename, extension, title, url, visibleURL, pasteboard);
4470
    setFileAndURLTypes(filename, extension, title, url, visibleURL, pasteboard);
4471
4471
4472
    if (archiveBuffer) {
4472
    if (archiveBuffer) {
4473
        auto nsData = archiveBuffer->createNSData();
4473
        auto nsData = archiveBuffer->makeContiguous()->createNSData();
4474
ALLOW_DEPRECATED_DECLARATIONS_BEGIN
4474
ALLOW_DEPRECATED_DECLARATIONS_BEGIN
4475
        [pasteboard setData:nsData.get() forType:(__bridge NSString *)kUTTypeWebArchive];
4475
        [pasteboard setData:nsData.get() forType:(__bridge NSString *)kUTTypeWebArchive];
4476
ALLOW_DEPRECATED_DECLARATIONS_END
4476
ALLOW_DEPRECATED_DECLARATIONS_END
Lines 4501-4507 void WebViewImpl::provideDataForPasteboard(NSPasteboard *pasteboard, NSString *t a/Source/WebKit/UIProcess/Cocoa/WebViewImpl.mm_sec3
4501
        return;
4501
        return;
4502
4502
4503
    if ([type isEqual:m_promisedImage->uti()] && m_promisedImage->data()) {
4503
    if ([type isEqual:m_promisedImage->uti()] && m_promisedImage->data()) {
4504
        if (auto platformData = m_promisedImage->data()->createNSData())
4504
        if (auto platformData = m_promisedImage->data()->makeContiguous()->createNSData())
4505
            [pasteboard setData:(__bridge NSData *)platformData.get() forType:type];
4505
            [pasteboard setData:(__bridge NSData *)platformData.get() forType:type];
4506
    }
4506
    }
4507
4507
Lines 4554-4560 NSArray *WebViewImpl::namesOfPromisedFilesDroppedAtDestination(NSURL *dropDestin a/Source/WebKit/UIProcess/Cocoa/WebViewImpl.mm_sec4
4554
    RetainPtr<NSData> data;
4554
    RetainPtr<NSData> data;
4555
4555
4556
    if (m_promisedImage) {
4556
    if (m_promisedImage) {
4557
        data = m_promisedImage->data()->createNSData();
4557
        data = m_promisedImage->data()->makeContiguous()->createNSData();
4558
        wrapper = adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:data.get()]);
4558
        wrapper = adoptNS([[NSFileWrapper alloc] initRegularFileWithContents:data.get()]);
4559
    } else
4559
    } else
4560
        wrapper = adoptNS([[NSFileWrapper alloc] initWithURL:[NSURL URLWithString:m_promisedURL] options:NSFileWrapperReadingImmediate error:nil]);
4560
        wrapper = adoptNS([[NSFileWrapper alloc] initWithURL:[NSURL URLWithString:m_promisedURL] options:NSFileWrapperReadingImmediate error:nil]);
- a/Source/WebKit/UIProcess/PageClient.h -1 / +1 lines
Lines 328-334 public: a/Source/WebKit/UIProcess/PageClient.h_sec1
328
#endif
328
#endif
329
329
330
#if USE(APPKIT)
330
#if USE(APPKIT)
331
    virtual void setPromisedDataForImage(const String& pasteboardName, Ref<WebCore::SharedBuffer>&& imageBuffer, const String& filename, const String& extension, const String& title, const String& url, const String& visibleURL, RefPtr<WebCore::SharedBuffer>&& archiveBuffer, const String& originIdentifier) = 0;
331
    virtual void setPromisedDataForImage(const String& pasteboardName, Ref<WebCore::FragmentedSharedBuffer>&& imageBuffer, const String& filename, const String& extension, const String& title, const String& url, const String& visibleURL, RefPtr<WebCore::FragmentedSharedBuffer>&& archiveBuffer, const String& originIdentifier) = 0;
332
#endif
332
#endif
333
333
334
    virtual WebCore::FloatRect convertToDeviceSpace(const WebCore::FloatRect&) = 0;
334
    virtual WebCore::FloatRect convertToDeviceSpace(const WebCore::FloatRect&) = 0;
- a/Source/WebKit/UIProcess/WebPageProxy.h -1 / +1 lines
Lines 259-265 class IntSize; a/Source/WebKit/UIProcess/WebPageProxy.h_sec1
259
class ProtectionSpace;
259
class ProtectionSpace;
260
class RunLoopObserver;
260
class RunLoopObserver;
261
class SelectionData;
261
class SelectionData;
262
class SharedBuffer;
262
class FragmentedSharedBuffer;
263
class SpeechRecognitionRequest;
263
class SpeechRecognitionRequest;
264
class TextIndicator;
264
class TextIndicator;
265
class ValidationBubble;
265
class ValidationBubble;
- a/Source/WebKit/UIProcess/WebURLSchemeTask.cpp -10 / +5 lines
Lines 51-56 WebURLSchemeTask::WebURLSchemeTask(WebURLSchemeHandler& handler, WebPageProxy& p a/Source/WebKit/UIProcess/WebURLSchemeTask.cpp_sec1
51
    , m_request(WTFMove(parameters.request))
51
    , m_request(WTFMove(parameters.request))
52
    , m_frameInfo(API::FrameInfo::create(WTFMove(parameters.frameInfo), &page))
52
    , m_frameInfo(API::FrameInfo::create(WTFMove(parameters.frameInfo), &page))
53
    , m_syncCompletionHandler(WTFMove(syncCompletionHandler))
53
    , m_syncCompletionHandler(WTFMove(syncCompletionHandler))
54
    , m_syncData(makeUniqueRef<SharedBufferBuilder>())
54
{
55
{
55
    ASSERT(RunLoop::isMain());
56
    ASSERT(RunLoop::isMain());
56
}
57
}
Lines 168-174 auto WebURLSchemeTask::didReceiveResponse(const ResourceResponse& response) -> E a/Source/WebKit/UIProcess/WebURLSchemeTask.cpp_sec2
168
    return ExceptionType::None;
169
    return ExceptionType::None;
169
}
170
}
170
171
171
auto WebURLSchemeTask::didReceiveData(Ref<SharedBuffer>&& buffer) -> ExceptionType
172
auto WebURLSchemeTask::didReceiveData(Ref<FragmentedSharedBuffer>&& buffer) -> ExceptionType
172
{
173
{
173
    ASSERT(RunLoop::isMain());
174
    ASSERT(RunLoop::isMain());
174
175
Lines 187-196 auto WebURLSchemeTask::didReceiveData(Ref<SharedBuffer>&& buffer) -> ExceptionTy a/Source/WebKit/UIProcess/WebURLSchemeTask.cpp_sec3
187
    m_dataSent = true;
188
    m_dataSent = true;
188
189
189
    if (isSync()) {
190
    if (isSync()) {
190
        if (m_syncData)
191
        m_syncData->append(WTFMove(buffer));
191
            m_syncData->append(WTFMove(buffer));
192
        else
193
            m_syncData = WTFMove(buffer);
194
        return ExceptionType::None;
192
        return ExceptionType::None;
195
    }
193
    }
196
194
Lines 217-228 auto WebURLSchemeTask::didComplete(const ResourceError& error) -> ExceptionType a/Source/WebKit/UIProcess/WebURLSchemeTask.cpp_sec4
217
    m_completed = true;
215
    m_completed = true;
218
    
216
    
219
    if (isSync()) {
217
    if (isSync()) {
220
        Vector<uint8_t> data;
218
        size_t size = m_syncData->size();
221
        if (m_syncData)
219
        Vector<uint8_t> data = { m_syncData->take()->makeContiguous()->data(), size };
222
            data = { m_syncData->data(), m_syncData->size() };
223
224
        m_syncCompletionHandler(m_syncResponse, error, WTFMove(data));
220
        m_syncCompletionHandler(m_syncResponse, error, WTFMove(data));
225
        m_syncData = nullptr;
226
    }
221
    }
227
222
228
    m_process->send(Messages::WebPage::URLSchemeTaskDidComplete(m_urlSchemeHandler->identifier(), m_resourceLoaderID, error), m_webPageID);
223
    m_process->send(Messages::WebPage::URLSchemeTaskDidComplete(m_urlSchemeHandler->identifier(), m_resourceLoaderID, error), m_webPageID);
- a/Source/WebKit/UIProcess/WebURLSchemeTask.h -3 / +5 lines
Lines 35-40 a/Source/WebKit/UIProcess/WebURLSchemeTask.h_sec1
35
#include <wtf/Lock.h>
35
#include <wtf/Lock.h>
36
#include <wtf/RefCounted.h>
36
#include <wtf/RefCounted.h>
37
#include <wtf/RefPtr.h>
37
#include <wtf/RefPtr.h>
38
#include <wtf/UniqueRef.h>
38
39
39
namespace API {
40
namespace API {
40
class FrameInfo;
41
class FrameInfo;
Lines 43-49 class FrameInfo; a/Source/WebKit/UIProcess/WebURLSchemeTask.h_sec2
43
namespace WebCore {
44
namespace WebCore {
44
class ResourceError;
45
class ResourceError;
45
class ResourceResponse;
46
class ResourceResponse;
46
class SharedBuffer;
47
class FragmentedSharedBuffer;
48
class SharedBufferBuilder;
47
}
49
}
48
50
49
namespace WebKit {
51
namespace WebKit {
Lines 84-90 public: a/Source/WebKit/UIProcess/WebURLSchemeTask.h_sec3
84
    ExceptionType willPerformRedirection(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&,  Function<void(WebCore::ResourceRequest&&)>&&);
86
    ExceptionType willPerformRedirection(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&,  Function<void(WebCore::ResourceRequest&&)>&&);
85
    ExceptionType didPerformRedirection(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&);
87
    ExceptionType didPerformRedirection(WebCore::ResourceResponse&&, WebCore::ResourceRequest&&);
86
    ExceptionType didReceiveResponse(const WebCore::ResourceResponse&);
88
    ExceptionType didReceiveResponse(const WebCore::ResourceResponse&);
87
    ExceptionType didReceiveData(Ref<WebCore::SharedBuffer>&&);
89
    ExceptionType didReceiveData(Ref<WebCore::FragmentedSharedBuffer>&&);
88
    ExceptionType didComplete(const WebCore::ResourceError&);
90
    ExceptionType didComplete(const WebCore::ResourceError&);
89
91
90
    void stop();
92
    void stop();
Lines 115-121 private: a/Source/WebKit/UIProcess/WebURLSchemeTask.h_sec4
115
117
116
    SyncLoadCompletionHandler m_syncCompletionHandler;
118
    SyncLoadCompletionHandler m_syncCompletionHandler;
117
    WebCore::ResourceResponse m_syncResponse;
119
    WebCore::ResourceResponse m_syncResponse;
118
    RefPtr<WebCore::SharedBuffer> m_syncData;
120
    UniqueRef<WebCore::SharedBufferBuilder> m_syncData;
119
121
120
    bool m_waitingForRedirectCompletionHandlerCallback { false };
122
    bool m_waitingForRedirectCompletionHandlerCallback { false };
121
};
123
};
- a/Source/WebKit/UIProcess/gtk/Clipboard.h -2 / +2 lines
Lines 36-42 typedef struct _GtkClipboard GtkClipboard; a/Source/WebKit/UIProcess/gtk/Clipboard.h_sec1
36
36
37
namespace WebCore {
37
namespace WebCore {
38
class SelectionData;
38
class SelectionData;
39
class SharedBuffer;
39
class FragmentedSharedBuffer;
40
}
40
}
41
41
42
namespace WebKit {
42
namespace WebKit {
Lines 55-61 public: a/Source/WebKit/UIProcess/gtk/Clipboard.h_sec2
55
    void formats(CompletionHandler<void(Vector<String>&&)>&&);
55
    void formats(CompletionHandler<void(Vector<String>&&)>&&);
56
    void readText(CompletionHandler<void(String&&)>&&);
56
    void readText(CompletionHandler<void(String&&)>&&);
57
    void readFilePaths(CompletionHandler<void(Vector<String>&&)>&&);
57
    void readFilePaths(CompletionHandler<void(Vector<String>&&)>&&);
58
    void readBuffer(const char*, CompletionHandler<void(Ref<WebCore::SharedBuffer>&&)>&&);
58
    void readBuffer(const char*, CompletionHandler<void(Ref<WebCore::FragmentedSharedBuffer>&&)>&&);
59
    void write(WebCore::SelectionData&&);
59
    void write(WebCore::SelectionData&&);
60
    void clear();
60
    void clear();
61
61
- a/Source/WebKit/UIProcess/gtk/ClipboardGtk3.cpp -3 / +3 lines
Lines 126-140 void Clipboard::readFilePaths(CompletionHandler<void(Vector<String>&&)>&& comple a/Source/WebKit/UIProcess/gtk/ClipboardGtk3.cpp_sec1
126
struct ReadBufferAsyncData {
126
struct ReadBufferAsyncData {
127
    WTF_MAKE_STRUCT_FAST_ALLOCATED;
127
    WTF_MAKE_STRUCT_FAST_ALLOCATED;
128
128
129
    explicit ReadBufferAsyncData(CompletionHandler<void(Ref<WebCore::SharedBuffer>&&)>&& handler)
129
    explicit ReadBufferAsyncData(CompletionHandler<void(Ref<WebCore::FragmentedSharedBuffer>&&)>&& handler)
130
        : completionHandler(WTFMove(handler))
130
        : completionHandler(WTFMove(handler))
131
    {
131
    {
132
    }
132
    }
133
133
134
    CompletionHandler<void(Ref<WebCore::SharedBuffer>&&)> completionHandler;
134
    CompletionHandler<void(Ref<WebCore::FragmentedSharedBuffer>&&)> completionHandler;
135
};
135
};
136
136
137
void Clipboard::readBuffer(const char* format, CompletionHandler<void(Ref<WebCore::SharedBuffer>&&)>&& completionHandler)
137
void Clipboard::readBuffer(const char* format, CompletionHandler<void(Ref<WebCore::FragmentedSharedBuffer>&&)>&& completionHandler)
138
{
138
{
139
    gtk_clipboard_request_contents(m_clipboard, gdk_atom_intern(format, TRUE), [](GtkClipboard*, GtkSelectionData* selection, gpointer userData) {
139
    gtk_clipboard_request_contents(m_clipboard, gdk_atom_intern(format, TRUE), [](GtkClipboard*, GtkSelectionData* selection, gpointer userData) {
140
        std::unique_ptr<ReadBufferAsyncData> data(static_cast<ReadBufferAsyncData*>(userData));
140
        std::unique_ptr<ReadBufferAsyncData> data(static_cast<ReadBufferAsyncData*>(userData));
- a/Source/WebKit/UIProcess/gtk/ClipboardGtk4.cpp -3 / +3 lines
Lines 120-134 void Clipboard::readFilePaths(CompletionHandler<void(Vector<String>&&)>&& comple a/Source/WebKit/UIProcess/gtk/ClipboardGtk4.cpp_sec1
120
struct ReadBufferAsyncData {
120
struct ReadBufferAsyncData {
121
    WTF_MAKE_STRUCT_FAST_ALLOCATED;
121
    WTF_MAKE_STRUCT_FAST_ALLOCATED;
122
122
123
    explicit ReadBufferAsyncData(CompletionHandler<void(Ref<WebCore::SharedBuffer>&&)>&& handler)
123
    explicit ReadBufferAsyncData(CompletionHandler<void(Ref<WebCore::FragmentedSharedBuffer>&&)>&& handler)
124
        : completionHandler(WTFMove(handler))
124
        : completionHandler(WTFMove(handler))
125
    {
125
    {
126
    }
126
    }
127
127
128
    CompletionHandler<void(Ref<WebCore::SharedBuffer>&&)> completionHandler;
128
    CompletionHandler<void(Ref<WebCore::FragmentedSharedBuffer>&&)> completionHandler;
129
};
129
};
130
130
131
void Clipboard::readBuffer(const char* format, CompletionHandler<void(Ref<WebCore::SharedBuffer>&&)>&& completionHandler)
131
void Clipboard::readBuffer(const char* format, CompletionHandler<void(Ref<WebCore::FragmentedSharedBuffer>&&)>&& completionHandler)
132
{
132
{
133
    const char* mimeTypes[] = { format, nullptr };
133
    const char* mimeTypes[] = { format, nullptr };
134
    gdk_clipboard_read_async(m_clipboard, mimeTypes, G_PRIORITY_DEFAULT, nullptr, [](GObject* clipboard, GAsyncResult* result, gpointer userData) {
134
    gdk_clipboard_read_async(m_clipboard, mimeTypes, G_PRIORITY_DEFAULT, nullptr, [](GObject* clipboard, GAsyncResult* result, gpointer userData) {
- a/Source/WebKit/UIProcess/mac/PageClientImplMac.h -2 / +2 lines
Lines 100-107 private: a/Source/WebKit/UIProcess/mac/PageClientImplMac.h_sec1
100
    void executeUndoRedo(UndoOrRedo) override;
100
    void executeUndoRedo(UndoOrRedo) override;
101
    bool executeSavedCommandBySelector(const String& selector) override;
101
    bool executeSavedCommandBySelector(const String& selector) override;
102
    void startDrag(const WebCore::DragItem&, const ShareableBitmap::Handle& image) override;
102
    void startDrag(const WebCore::DragItem&, const ShareableBitmap::Handle& image) override;
103
    void setPromisedDataForImage(const String& pasteboardName, Ref<WebCore::SharedBuffer>&& imageBuffer, const String& filename, const String& extension, const String& title,
103
    void setPromisedDataForImage(const String& pasteboardName, Ref<WebCore::FragmentedSharedBuffer>&& imageBuffer, const String& filename, const String& extension, const String& title,
104
        const String& url, const String& visibleURL, RefPtr<WebCore::SharedBuffer>&& archiveBuffer, const String& originIdentifier) override;
104
        const String& url, const String& visibleURL, RefPtr<WebCore::FragmentedSharedBuffer>&& archiveBuffer, const String& originIdentifier) override;
105
    void updateSecureInputState() override;
105
    void updateSecureInputState() override;
106
    void resetSecureInputState() override;
106
    void resetSecureInputState() override;
107
    void notifyInputContextAboutDiscardedComposition() override;
107
    void notifyInputContextAboutDiscardedComposition() override;
- a/Source/WebKit/UIProcess/mac/PageClientImplMac.mm -1 / +1 lines
Lines 400-406 void PageClientImpl::startDrag(const WebCore::DragItem& item, const ShareableBit a/Source/WebKit/UIProcess/mac/PageClientImplMac.mm_sec1
400
    m_impl->startDrag(item, image);
400
    m_impl->startDrag(item, image);
401
}
401
}
402
402
403
void PageClientImpl::setPromisedDataForImage(const String& pasteboardName, Ref<SharedBuffer>&& imageBuffer, const String& filename, const String& extension, const String& title, const String& url, const String& visibleURL, RefPtr<SharedBuffer>&& archiveBuffer, const String& originIdentifier)
403
void PageClientImpl::setPromisedDataForImage(const String& pasteboardName, Ref<FragmentedSharedBuffer>&& imageBuffer, const String& filename, const String& extension, const String& title, const String& url, const String& visibleURL, RefPtr<FragmentedSharedBuffer>&& archiveBuffer, const String& originIdentifier)
404
{
404
{
405
    auto image = BitmapImage::create();
405
    auto image = BitmapImage::create();
406
    image->setData(WTFMove(imageBuffer), true);
406
    image->setData(WTFMove(imageBuffer), true);
- a/Source/WebKit/UIProcess/mac/WebPageProxyMac.mm -1 / +1 lines
Lines 277-283 void WebPageProxy::setPromisedDataForImage(const String& pasteboardName, const S a/Source/WebKit/UIProcess/mac/WebPageProxyMac.mm_sec1
277
        return;
277
        return;
278
    auto imageBuffer = sharedMemoryImage->createSharedBuffer(imageHandle.dataSize);
278
    auto imageBuffer = sharedMemoryImage->createSharedBuffer(imageHandle.dataSize);
279
279
280
    RefPtr<SharedBuffer> archiveBuffer;
280
    RefPtr<FragmentedSharedBuffer> archiveBuffer;
281
    if (!archiveHandle.handle.isNull()) {
281
    if (!archiveHandle.handle.isNull()) {
282
        auto sharedMemoryArchive = SharedMemory::map(archiveHandle.handle, SharedMemory::Protection::ReadOnly);
282
        auto sharedMemoryArchive = SharedMemory::map(archiveHandle.handle, SharedMemory::Protection::ReadOnly);
283
        if (!sharedMemoryArchive)
283
        if (!sharedMemoryArchive)
- a/Source/WebKit/WebProcess/GPU/media/RemoteCDM.cpp -2 / +2 lines
Lines 84-90 bool RemoteCDM::supportsSessionTypeWithConfiguration(const CDMSessionType&, cons a/Source/WebKit/WebProcess/GPU/media/RemoteCDM.cpp_sec1
84
    return false;
84
    return false;
85
}
85
}
86
86
87
bool RemoteCDM::supportsInitData(const AtomString& type, const SharedBuffer& data) const
87
bool RemoteCDM::supportsInitData(const AtomString& type, const FragmentedSharedBuffer& data) const
88
{
88
{
89
    // This check will be done, later, inside RemoteCDMInstanceSessionProxy::requestLicense().
89
    // This check will be done, later, inside RemoteCDMInstanceSessionProxy::requestLicense().
90
    return true;
90
    return true;
Lines 129-135 void RemoteCDM::loadAndInitialize() a/Source/WebKit/WebProcess/GPU/media/RemoteCDM.cpp_sec2
129
    m_factory->gpuProcessConnection().connection().send(Messages::RemoteCDMProxy::LoadAndInitialize(), m_identifier);
129
    m_factory->gpuProcessConnection().connection().send(Messages::RemoteCDMProxy::LoadAndInitialize(), m_identifier);
130
}
130
}
131
131
132
RefPtr<SharedBuffer> RemoteCDM::sanitizeResponse(const SharedBuffer& response) const
132
RefPtr<FragmentedSharedBuffer> RemoteCDM::sanitizeResponse(const FragmentedSharedBuffer& response) const
133
{
133
{
134
    // This check will be done, later, inside RemoteCDMInstanceSessionProxy::updateLicense().
134
    // This check will be done, later, inside RemoteCDMInstanceSessionProxy::updateLicense().
135
    return response.copy();
135
    return response.copy();
- a/Source/WebKit/WebProcess/GPU/media/RemoteCDM.h -2 / +2 lines
Lines 48-60 private: a/Source/WebKit/WebProcess/GPU/media/RemoteCDM.h_sec1
48
    bool supportsConfiguration(const WebCore::CDMKeySystemConfiguration&) const final;
48
    bool supportsConfiguration(const WebCore::CDMKeySystemConfiguration&) const final;
49
    bool supportsConfigurationWithRestrictions(const WebCore::CDMKeySystemConfiguration&, const WebCore::CDMRestrictions&) const final;
49
    bool supportsConfigurationWithRestrictions(const WebCore::CDMKeySystemConfiguration&, const WebCore::CDMRestrictions&) const final;
50
    bool supportsSessionTypeWithConfiguration(const WebCore::CDMSessionType&, const WebCore::CDMKeySystemConfiguration&) const final;
50
    bool supportsSessionTypeWithConfiguration(const WebCore::CDMSessionType&, const WebCore::CDMKeySystemConfiguration&) const final;
51
    bool supportsInitData(const AtomString&, const WebCore::SharedBuffer&) const final;
51
    bool supportsInitData(const AtomString&, const WebCore::FragmentedSharedBuffer&) const final;
52
    WebCore::CDMRequirement distinctiveIdentifiersRequirement(const WebCore::CDMKeySystemConfiguration&, const WebCore::CDMRestrictions&) const final;
52
    WebCore::CDMRequirement distinctiveIdentifiersRequirement(const WebCore::CDMKeySystemConfiguration&, const WebCore::CDMRestrictions&) const final;
53
    WebCore::CDMRequirement persistentStateRequirement(const WebCore::CDMKeySystemConfiguration&, const WebCore::CDMRestrictions&) const final;
53
    WebCore::CDMRequirement persistentStateRequirement(const WebCore::CDMKeySystemConfiguration&, const WebCore::CDMRestrictions&) const final;
54
    bool distinctiveIdentifiersAreUniquePerOriginAndClearable(const WebCore::CDMKeySystemConfiguration&) const final;
54
    bool distinctiveIdentifiersAreUniquePerOriginAndClearable(const WebCore::CDMKeySystemConfiguration&) const final;
55
    RefPtr<WebCore::CDMInstance> createInstance() final;
55
    RefPtr<WebCore::CDMInstance> createInstance() final;
56
    void loadAndInitialize() final;
56
    void loadAndInitialize() final;
57
    RefPtr<WebCore::SharedBuffer> sanitizeResponse(const WebCore::SharedBuffer&) const final;
57
    RefPtr<WebCore::FragmentedSharedBuffer> sanitizeResponse(const WebCore::FragmentedSharedBuffer&) const final;
58
    std::optional<String> sanitizeSessionId(const String&) const final;
58
    std::optional<String> sanitizeSessionId(const String&) const final;
59
59
60
    Vector<AtomString> supportedInitDataTypes() const final { return m_configuration.supportedInitDataTypes; }
60
    Vector<AtomString> supportedInitDataTypes() const final { return m_configuration.supportedInitDataTypes; }
- a/Source/WebKit/WebProcess/GPU/media/RemoteCDMInstance.cpp -1 / +1 lines
Lines 78-84 void RemoteCDMInstance::initializeWithConfiguration(const WebCore::CDMKeySystemC a/Source/WebKit/WebProcess/GPU/media/RemoteCDMInstance.cpp_sec1
78
    m_factory->gpuProcessConnection().connection().sendWithAsyncReply(Messages::RemoteCDMInstanceProxy::InitializeWithConfiguration(configuration, distinctiveIdentifiers, persistentState), WTFMove(callback), m_identifier);
78
    m_factory->gpuProcessConnection().connection().sendWithAsyncReply(Messages::RemoteCDMInstanceProxy::InitializeWithConfiguration(configuration, distinctiveIdentifiers, persistentState), WTFMove(callback), m_identifier);
79
}
79
}
80
80
81
void RemoteCDMInstance::setServerCertificate(Ref<WebCore::SharedBuffer>&& certificate, SuccessCallback&& callback)
81
void RemoteCDMInstance::setServerCertificate(Ref<WebCore::FragmentedSharedBuffer>&& certificate, SuccessCallback&& callback)
82
{
82
{
83
    if (!m_factory) {
83
    if (!m_factory) {
84
        callback(Failed);
84
        callback(Failed);
- a/Source/WebKit/WebProcess/GPU/media/RemoteCDMInstance.h -1 / +1 lines
Lines 54-60 private: a/Source/WebKit/WebProcess/GPU/media/RemoteCDMInstance.h_sec1
54
54
55
    ImplementationType implementationType() const final { return ImplementationType::Remote; }
55
    ImplementationType implementationType() const final { return ImplementationType::Remote; }
56
    void initializeWithConfiguration(const WebCore::CDMKeySystemConfiguration&, AllowDistinctiveIdentifiers, AllowPersistentState, SuccessCallback&&) final;
56
    void initializeWithConfiguration(const WebCore::CDMKeySystemConfiguration&, AllowDistinctiveIdentifiers, AllowPersistentState, SuccessCallback&&) final;
57
    void setServerCertificate(Ref<WebCore::SharedBuffer>&&, SuccessCallback&&) final;
57
    void setServerCertificate(Ref<WebCore::FragmentedSharedBuffer>&&, SuccessCallback&&) final;
58
    void setStorageDirectory(const String&) final;
58
    void setStorageDirectory(const String&) final;
59
    const String& keySystem() const final { return m_configuration.keySystem; }
59
    const String& keySystem() const final { return m_configuration.keySystem; }
60
    RefPtr<WebCore::CDMInstanceSession> createSession() final;
60
    RefPtr<WebCore::CDMInstanceSession> createSession() final;
- a/Source/WebKit/WebProcess/GPU/media/RemoteCDMInstanceSession.cpp -3 / +3 lines
Lines 49-55 RemoteCDMInstanceSession::RemoteCDMInstanceSession(WeakPtr<RemoteCDMFactory>&& f a/Source/WebKit/WebProcess/GPU/media/RemoteCDMInstanceSession.cpp_sec1
49
{
49
{
50
}
50
}
51
51
52
void RemoteCDMInstanceSession::requestLicense(LicenseType type, const AtomString& initDataType, Ref<SharedBuffer>&& initData, LicenseCallback&& callback)
52
void RemoteCDMInstanceSession::requestLicense(LicenseType type, const AtomString& initDataType, Ref<FragmentedSharedBuffer>&& initData, LicenseCallback&& callback)
53
{
53
{
54
    if (!m_factory) {
54
    if (!m_factory) {
55
        callback(SharedBuffer::create(), emptyString(), false, Failed);
55
        callback(SharedBuffer::create(), emptyString(), false, Failed);
Lines 65-71 void RemoteCDMInstanceSession::requestLicense(LicenseType type, const AtomString a/Source/WebKit/WebProcess/GPU/media/RemoteCDMInstanceSession.cpp_sec2
65
    }, m_identifier);
65
    }, m_identifier);
66
}
66
}
67
67
68
void RemoteCDMInstanceSession::updateLicense(const String& sessionId, LicenseType type, Ref<SharedBuffer>&& response, LicenseUpdateCallback&& callback)
68
void RemoteCDMInstanceSession::updateLicense(const String& sessionId, LicenseType type, Ref<FragmentedSharedBuffer>&& response, LicenseUpdateCallback&& callback)
69
{
69
{
70
    if (!m_factory) {
70
    if (!m_factory) {
71
        callback(false, std::nullopt, std::nullopt, std::nullopt, Failed);
71
        callback(false, std::nullopt, std::nullopt, std::nullopt, Failed);
Lines 109-115 void RemoteCDMInstanceSession::removeSessionData(const String& sessionId, Licens a/Source/WebKit/WebProcess/GPU/media/RemoteCDMInstanceSession.cpp_sec3
109
    }
109
    }
110
110
111
    m_factory->gpuProcessConnection().connection().sendWithAsyncReply(Messages::RemoteCDMInstanceSessionProxy::RemoveSessionData(sessionId, type), [callback = WTFMove(callback)] (KeyStatusVector&& changedKeys, std::optional<IPC::SharedBufferCopy>&& message, bool succeeded) mutable {
111
    m_factory->gpuProcessConnection().connection().sendWithAsyncReply(Messages::RemoteCDMInstanceSessionProxy::RemoveSessionData(sessionId, type), [callback = WTFMove(callback)] (KeyStatusVector&& changedKeys, std::optional<IPC::SharedBufferCopy>&& message, bool succeeded) mutable {
112
        std::optional<Ref<SharedBuffer>> realMessage = std::nullopt;
112
        std::optional<Ref<FragmentedSharedBuffer>> realMessage = std::nullopt;
113
        if (message && message.value().buffer())
113
        if (message && message.value().buffer())
114
            realMessage = message.value().buffer().releaseNonNull();
114
            realMessage = message.value().buffer().releaseNonNull();
115
        callback(WTFMove(changedKeys), WTFMove(realMessage), succeeded ? Succeeded : Failed);
115
        callback(WTFMove(changedKeys), WTFMove(realMessage), succeeded ? Succeeded : Failed);
- a/Source/WebKit/WebProcess/GPU/media/RemoteCDMInstanceSession.h -2 / +2 lines
Lines 59-66 private: a/Source/WebKit/WebProcess/GPU/media/RemoteCDMInstanceSession.h_sec1
59
59
60
    void setClient(WeakPtr<WebCore::CDMInstanceSessionClient>&& client) final { m_client = WTFMove(client); }
60
    void setClient(WeakPtr<WebCore::CDMInstanceSessionClient>&& client) final { m_client = WTFMove(client); }
61
    void clearClient() final { m_client = nullptr; }
61
    void clearClient() final { m_client = nullptr; }
62
    void requestLicense(LicenseType, const AtomString& initDataType, Ref<WebCore::SharedBuffer>&& initData, LicenseCallback&&) final;
62
    void requestLicense(LicenseType, const AtomString& initDataType, Ref<WebCore::FragmentedSharedBuffer>&& initData, LicenseCallback&&) final;
63
    void updateLicense(const String& sessionId, LicenseType, Ref<WebCore::SharedBuffer>&& response, LicenseUpdateCallback&&) final;
63
    void updateLicense(const String& sessionId, LicenseType, Ref<WebCore::FragmentedSharedBuffer>&& response, LicenseUpdateCallback&&) final;
64
    void loadSession(LicenseType, const String& sessionId, const String& origin, LoadSessionCallback&&) final;
64
    void loadSession(LicenseType, const String& sessionId, const String& origin, LoadSessionCallback&&) final;
65
    void closeSession(const String& sessionId, CloseSessionCallback&&) final;
65
    void closeSession(const String& sessionId, CloseSessionCallback&&) final;
66
    void removeSessionData(const String& sessionId, LicenseType, RemoveSessionDataCallback&&) final;
66
    void removeSessionData(const String& sessionId, LicenseType, RemoveSessionDataCallback&&) final;
- a/Source/WebKit/WebProcess/GPU/media/RemoteImageDecoderAVF.cpp -1 / +1 lines
Lines 200-206 void RemoteImageDecoderAVF::setExpectedContentSize(long long expectedContentSize a/Source/WebKit/WebProcess/GPU/media/RemoteImageDecoderAVF.cpp_sec1
200
200
201
// If allDataReceived is true, the caller expects encodedDataStatus() to be >= EncodedDataStatus::SizeAvailable
201
// If allDataReceived is true, the caller expects encodedDataStatus() to be >= EncodedDataStatus::SizeAvailable
202
// after this function returns (in the same run loop).
202
// after this function returns (in the same run loop).
203
void RemoteImageDecoderAVF::setData(SharedBuffer& data, bool allDataReceived)
203
void RemoteImageDecoderAVF::setData(FragmentedSharedBuffer& data, bool allDataReceived)
204
{
204
{
205
    if (!m_gpuProcessConnection)
205
    if (!m_gpuProcessConnection)
206
        return;
206
        return;
- a/Source/WebKit/WebProcess/GPU/media/RemoteImageDecoderAVF.h -2 / +2 lines
Lines 45-51 class RemoteImageDecoderAVF final a/Source/WebKit/WebProcess/GPU/media/RemoteImageDecoderAVF.h_sec1
45
    : public WebCore::ImageDecoder
45
    : public WebCore::ImageDecoder
46
    , public CanMakeWeakPtr<RemoteImageDecoderAVF> {
46
    , public CanMakeWeakPtr<RemoteImageDecoderAVF> {
47
public:
47
public:
48
    static Ref<RemoteImageDecoderAVF> create(RemoteImageDecoderAVFManager& manager, const WebCore::ImageDecoderIdentifier& identifier, WebCore::SharedBuffer&, const String& mimeType)
48
    static Ref<RemoteImageDecoderAVF> create(RemoteImageDecoderAVFManager& manager, const WebCore::ImageDecoderIdentifier& identifier, WebCore::FragmentedSharedBuffer&, const String& mimeType)
49
    {
49
    {
50
        return adoptRef(*new RemoteImageDecoderAVF(manager, identifier, mimeType));
50
        return adoptRef(*new RemoteImageDecoderAVF(manager, identifier, mimeType));
51
    }
51
    }
Lines 80-86 public: a/Source/WebKit/WebProcess/GPU/media/RemoteImageDecoderAVF.h_sec2
80
    WebCore::PlatformImagePtr createFrameImageAtIndex(size_t, WebCore::SubsamplingLevel = WebCore::SubsamplingLevel::Default, const WebCore::DecodingOptions& = WebCore::DecodingOptions(WebCore::DecodingMode::Synchronous)) final;
80
    WebCore::PlatformImagePtr createFrameImageAtIndex(size_t, WebCore::SubsamplingLevel = WebCore::SubsamplingLevel::Default, const WebCore::DecodingOptions& = WebCore::DecodingOptions(WebCore::DecodingMode::Synchronous)) final;
81
81
82
    void setExpectedContentSize(long long) final;
82
    void setExpectedContentSize(long long) final;
83
    void setData(WebCore::SharedBuffer&, bool allDataReceived) final;
83
    void setData(WebCore::FragmentedSharedBuffer&, bool allDataReceived) final;
84
    bool isAllDataReceived() const final { return m_isAllDataReceived; }
84
    bool isAllDataReceived() const final { return m_isAllDataReceived; }
85
    void clearFrameBufferCache(size_t) final;
85
    void clearFrameBufferCache(size_t) final;
86
86
- a/Source/WebKit/WebProcess/GPU/media/RemoteImageDecoderAVFManager.cpp -2 / +2 lines
Lines 39-45 namespace WebKit { a/Source/WebKit/WebProcess/GPU/media/RemoteImageDecoderAVFManager.cpp_sec1
39
39
40
using namespace WebCore;
40
using namespace WebCore;
41
41
42
RefPtr<RemoteImageDecoderAVF> RemoteImageDecoderAVFManager::createImageDecoder(SharedBuffer& data, const String& mimeType, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
42
RefPtr<RemoteImageDecoderAVF> RemoteImageDecoderAVFManager::createImageDecoder(FragmentedSharedBuffer& data, const String& mimeType, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
43
{
43
{
44
    std::optional<ImageDecoderIdentifier> imageDecoderIdentifier;
44
    std::optional<ImageDecoderIdentifier> imageDecoderIdentifier;
45
    IPC::SharedBufferDataReference dataReference { data };
45
    IPC::SharedBufferDataReference dataReference { data };
Lines 108-114 void RemoteImageDecoderAVFManager::setUseGPUProcess(bool useGPUProcess) a/Source/WebKit/WebProcess/GPU/media/RemoteImageDecoderAVFManager.cpp_sec2
108
    ImageDecoder::installFactory({
108
    ImageDecoder::installFactory({
109
        RemoteImageDecoderAVF::supportsMediaType,
109
        RemoteImageDecoderAVF::supportsMediaType,
110
        RemoteImageDecoderAVF::canDecodeType,
110
        RemoteImageDecoderAVF::canDecodeType,
111
        [this](SharedBuffer& data, const String& mimeType, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption) {
111
        [this](FragmentedSharedBuffer& data, const String& mimeType, AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption) {
112
            return createImageDecoder(data, mimeType, alphaOption, gammaAndColorProfileOption);
112
            return createImageDecoder(data, mimeType, alphaOption, gammaAndColorProfileOption);
113
        }
113
        }
114
    });
114
    });
- a/Source/WebKit/WebProcess/GPU/media/RemoteImageDecoderAVFManager.h -1 / +1 lines
Lines 59-65 public: a/Source/WebKit/WebProcess/GPU/media/RemoteImageDecoderAVFManager.h_sec1
59
    GPUProcessConnection& ensureGPUProcessConnection();
59
    GPUProcessConnection& ensureGPUProcessConnection();
60
60
61
private:
61
private:
62
    RefPtr<RemoteImageDecoderAVF> createImageDecoder(WebCore::SharedBuffer& data, const String& mimeType, WebCore::AlphaOption, WebCore::GammaAndColorProfileOption);
62
    RefPtr<RemoteImageDecoderAVF> createImageDecoder(WebCore::FragmentedSharedBuffer& data, const String& mimeType, WebCore::AlphaOption, WebCore::GammaAndColorProfileOption);
63
63
64
    // GPUProcessConnection::Client.
64
    // GPUProcessConnection::Client.
65
    void gpuProcessConnectionDidClose(GPUProcessConnection&) final;
65
    void gpuProcessConnectionDidClose(GPUProcessConnection&) final;
- a/Source/WebKit/WebProcess/GPU/webrtc/MediaRecorderPrivate.cpp -2 / +2 lines
Lines 165-174 void MediaRecorderPrivate::storageChanged(SharedMemory* storage, const WebCore:: a/Source/WebKit/WebProcess/GPU/webrtc/MediaRecorderPrivate.cpp_sec1
165
    m_connection->send(Messages::RemoteMediaRecorder::AudioSamplesStorageChanged { SharedMemory::IPCHandle { WTFMove(handle), dataSize }, format, frameCount }, m_identifier);
165
    m_connection->send(Messages::RemoteMediaRecorder::AudioSamplesStorageChanged { SharedMemory::IPCHandle { WTFMove(handle), dataSize }, format, frameCount }, m_identifier);
166
}
166
}
167
167
168
void MediaRecorderPrivate::fetchData(CompletionHandler<void(RefPtr<WebCore::SharedBuffer>&&, const String& mimeType, double)>&& completionHandler)
168
void MediaRecorderPrivate::fetchData(CompletionHandler<void(RefPtr<WebCore::FragmentedSharedBuffer>&&, const String& mimeType, double)>&& completionHandler)
169
{
169
{
170
    m_connection->sendWithAsyncReply(Messages::RemoteMediaRecorder::FetchData { }, [completionHandler = WTFMove(completionHandler), mimeType = mimeType()](auto&& data, double timeCode) mutable {
170
    m_connection->sendWithAsyncReply(Messages::RemoteMediaRecorder::FetchData { }, [completionHandler = WTFMove(completionHandler), mimeType = mimeType()](auto&& data, double timeCode) mutable {
171
        RefPtr<SharedBuffer> buffer;
171
        RefPtr<FragmentedSharedBuffer> buffer;
172
        if (data.size())
172
        if (data.size())
173
            buffer = SharedBuffer::create(data.data(), data.size());
173
            buffer = SharedBuffer::create(data.data(), data.size());
174
        completionHandler(WTFMove(buffer), mimeType, timeCode);
174
        completionHandler(WTFMove(buffer), mimeType, timeCode);
- a/Source/WebKit/WebProcess/GPU/webrtc/MediaRecorderPrivate.h -1 / +1 lines
Lines 57-63 public: a/Source/WebKit/WebProcess/GPU/webrtc/MediaRecorderPrivate.h_sec1
57
private:
57
private:
58
    // WebCore::MediaRecorderPrivate
58
    // WebCore::MediaRecorderPrivate
59
    void videoSampleAvailable(WebCore::MediaSample&, WebCore::VideoSampleMetadata) final;
59
    void videoSampleAvailable(WebCore::MediaSample&, WebCore::VideoSampleMetadata) final;
60
    void fetchData(CompletionHandler<void(RefPtr<WebCore::SharedBuffer>&&, const String& mimeType, double)>&&) final;
60
    void fetchData(CompletionHandler<void(RefPtr<WebCore::FragmentedSharedBuffer>&&, const String& mimeType, double)>&&) final;
61
    void stopRecording(CompletionHandler<void()>&&) final;
61
    void stopRecording(CompletionHandler<void()>&&) final;
62
    void startRecording(StartRecordingCallback&&) final;
62
    void startRecording(StartRecordingCallback&&) final;
63
    void audioSamplesAvailable(const WTF::MediaTime&, const WebCore::PlatformAudioData&, const WebCore::AudioStreamDescription&, size_t) final;
63
    void audioSamplesAvailable(const WTF::MediaTime&, const WebCore::PlatformAudioData&, const WebCore::AudioStreamDescription&, size_t) final;
- a/Source/WebKit/WebProcess/InjectedBundle/API/APIInjectedBundleEditorClient.h -1 / +1 lines
Lines 31-39 a/Source/WebKit/WebProcess/InjectedBundle/API/APIInjectedBundleEditorClient.h_sec1
31
#include <wtf/text/WTFString.h>
31
#include <wtf/text/WTFString.h>
32
32
33
namespace WebCore {
33
namespace WebCore {
34
class SharedBuffer;
34
class DocumentFragment;
35
class DocumentFragment;
35
class Node;
36
class Node;
36
class SharedBuffer;
37
class StyleProperties;
37
class StyleProperties;
38
struct SimpleRange;
38
struct SimpleRange;
39
}
39
}
- a/Source/WebKit/WebProcess/InjectedBundle/API/APIInjectedBundlePageLoaderClient.h -2 / +2 lines
Lines 36-42 class DOMWindowExtension; a/Source/WebKit/WebProcess/InjectedBundle/API/APIInjectedBundlePageLoaderClient.h_sec1
36
class DOMWrapperWorld;
36
class DOMWrapperWorld;
37
class ResourceError;
37
class ResourceError;
38
class ResourceRequest;
38
class ResourceRequest;
39
class SharedBuffer;
39
class FragmentedSharedBuffer;
40
}
40
}
41
41
42
namespace WebKit {
42
namespace WebKit {
Lines 56-62 public: a/Source/WebKit/WebProcess/InjectedBundle/API/APIInjectedBundlePageLoaderClient.h_sec2
56
    virtual ~PageLoaderClient() = default;
56
    virtual ~PageLoaderClient() = default;
57
57
58
    virtual void willLoadURLRequest(WebKit::WebPage&, const WebCore::ResourceRequest&, API::Object*) { }
58
    virtual void willLoadURLRequest(WebKit::WebPage&, const WebCore::ResourceRequest&, API::Object*) { }
59
    virtual void willLoadDataRequest(WebKit::WebPage&, const WebCore::ResourceRequest&, WebCore::SharedBuffer*, const WTF::String&, const WTF::String&, const WTF::URL&, API::Object*) { }
59
    virtual void willLoadDataRequest(WebKit::WebPage&, const WebCore::ResourceRequest&, WebCore::FragmentedSharedBuffer*, const WTF::String&, const WTF::String&, const WTF::URL&, API::Object*) { }
60
60
61
    virtual void didStartProvisionalLoadForFrame(WebKit::WebPage&, WebKit::WebFrame&, RefPtr<API::Object>&) { }
61
    virtual void didStartProvisionalLoadForFrame(WebKit::WebPage&, WebKit::WebFrame&, RefPtr<API::Object>&) { }
62
    virtual void didReceiveServerRedirectForProvisionalLoadForFrame(WebKit::WebPage&, WebKit::WebFrame&, RefPtr<API::Object>&) { }
62
    virtual void didReceiveServerRedirectForProvisionalLoadForFrame(WebKit::WebPage&, WebKit::WebFrame&, RefPtr<API::Object>&) { }
- a/Source/WebKit/WebProcess/InjectedBundle/InjectedBundlePageLoaderClient.cpp -4 / +5 lines
Lines 62-79 void InjectedBundlePageLoaderClient::willLoadURLRequest(WebPage& page, const Res a/Source/WebKit/WebProcess/InjectedBundle/InjectedBundlePageLoaderClient.cpp_sec1
62
static void releaseSharedBuffer(unsigned char*, const void* data)
62
static void releaseSharedBuffer(unsigned char*, const void* data)
63
{
63
{
64
    // Balanced by ref() in InjectedBundlePageLoaderClient::willLoadDataRequest().
64
    // Balanced by ref() in InjectedBundlePageLoaderClient::willLoadDataRequest().
65
    static_cast<SharedBuffer*>(const_cast<void*>(data))->deref();
65
    static_cast<const SharedBuffer*>(data)->deref();
66
}
66
}
67
67
68
void InjectedBundlePageLoaderClient::willLoadDataRequest(WebPage& page, const ResourceRequest& request, SharedBuffer* sharedBuffer, const String& MIMEType, const String& encodingName, const URL& unreachableURL, API::Object* userData)
68
void InjectedBundlePageLoaderClient::willLoadDataRequest(WebPage& page, const ResourceRequest& request, FragmentedSharedBuffer* sharedBuffer, const String& MIMEType, const String& encodingName, const URL& unreachableURL, API::Object* userData)
69
{
69
{
70
    if (!m_client.willLoadDataRequest)
70
    if (!m_client.willLoadDataRequest)
71
        return;
71
        return;
72
72
73
    RefPtr<API::Data> data;
73
    RefPtr<API::Data> data;
74
    if (sharedBuffer) {
74
    if (sharedBuffer) {
75
        sharedBuffer->ref();
75
        auto contiguousBuffer = sharedBuffer->makeContiguous();
76
        data = API::Data::createWithoutCopying((const unsigned char*)sharedBuffer->data(), sharedBuffer->size(), releaseSharedBuffer, sharedBuffer);
76
        contiguousBuffer->ref();
77
        data = API::Data::createWithoutCopying(contiguousBuffer->data(), contiguousBuffer->size(), releaseSharedBuffer, contiguousBuffer.ptr());
77
    }
78
    }
78
79
79
    m_client.willLoadDataRequest(toAPI(&page), toAPI(request), toAPI(data.get()), toAPI(MIMEType.impl()), toAPI(encodingName.impl()), toURLRef(unreachableURL.string().impl()), toAPI(userData), m_client.base.clientInfo);
80
    m_client.willLoadDataRequest(toAPI(&page), toAPI(request), toAPI(data.get()), toAPI(MIMEType.impl()), toAPI(encodingName.impl()), toURLRef(unreachableURL.string().impl()), toAPI(userData), m_client.base.clientInfo);
- a/Source/WebKit/WebProcess/InjectedBundle/InjectedBundlePageLoaderClient.h -1 / +1 lines
Lines 47-53 public: a/Source/WebKit/WebProcess/InjectedBundle/InjectedBundlePageLoaderClient.h_sec1
47
    explicit InjectedBundlePageLoaderClient(const WKBundlePageLoaderClientBase*);
47
    explicit InjectedBundlePageLoaderClient(const WKBundlePageLoaderClientBase*);
48
48
49
    void willLoadURLRequest(WebPage&, const WebCore::ResourceRequest&, API::Object*) override;
49
    void willLoadURLRequest(WebPage&, const WebCore::ResourceRequest&, API::Object*) override;
50
    void willLoadDataRequest(WebPage&, const WebCore::ResourceRequest&, WebCore::SharedBuffer*, const WTF::String&, const WTF::String&, const URL&, API::Object*) override;
50
    void willLoadDataRequest(WebPage&, const WebCore::ResourceRequest&, WebCore::FragmentedSharedBuffer*, const WTF::String&, const WTF::String&, const URL&, API::Object*) override;
51
51
52
    void didStartProvisionalLoadForFrame(WebPage&, WebFrame&, RefPtr<API::Object>&) override;
52
    void didStartProvisionalLoadForFrame(WebPage&, WebFrame&, RefPtr<API::Object>&) override;
53
    void didReceiveServerRedirectForProvisionalLoadForFrame(WebPage&, WebFrame&, RefPtr<API::Object>&) override;
53
    void didReceiveServerRedirectForProvisionalLoadForFrame(WebPage&, WebFrame&, RefPtr<API::Object>&) override;
- a/Source/WebKit/WebProcess/Model/mac/ARKitInlinePreviewModelPlayerMac.mm -1 / +1 lines
Lines 106-112 void ARKitInlinePreviewModelPlayerMac::createFile(WebCore::Model& modelSource) a/Source/WebKit/WebProcess/Model/mac/ARKitInlinePreviewModelPlayerMac.mm_sec1
106
    if (file <= 0)
106
    if (file <= 0)
107
        return;
107
        return;
108
108
109
    FileSystem::writeToFile(file, modelSource.data()->data(), modelSource.data()->size());
109
    FileSystem::writeToFile(file, modelSource.data()->makeContiguous()->data(), modelSource.data()->size());
110
    FileSystem::closeFile(file);
110
    FileSystem::closeFile(file);
111
    m_filePath = filePath;
111
    m_filePath = filePath;
112
}
112
}
- a/Source/WebKit/WebProcess/Network/NetworkProcessConnection.cpp -2 / +2 lines
Lines 281-289 void NetworkProcessConnection::didCacheResource(const ResourceRequest& request, a/Source/WebKit/WebProcess/Network/NetworkProcessConnection.cpp_sec1
281
    if (!resource)
281
    if (!resource)
282
        return;
282
        return;
283
    
283
    
284
    RefPtr<SharedBuffer> buffer = handle.tryWrapInSharedBuffer();
284
    auto buffer = handle.tryWrapInSharedBuffer();
285
    if (!buffer) {
285
    if (!buffer) {
286
        LOG_ERROR("Unable to create SharedBuffer from ShareableResource handle for resource url %s", request.url().string().utf8().data());
286
        LOG_ERROR("Unable to create FragmentedSharedBuffer from ShareableResource handle for resource url %s", request.url().string().utf8().data());
287
        return;
287
        return;
288
    }
288
    }
289
289
- a/Source/WebKit/WebProcess/Network/WebResourceLoader.cpp -3 / +3 lines
Lines 155-161 void WebResourceLoader::didReceiveResponse(const ResourceResponse& response, boo a/Source/WebKit/WebProcess/Network/WebResourceLoader.cpp_sec1
155
    if (InspectorInstrumentationWebKit::shouldInterceptResponse(m_coreLoader->frame(), response)) {
155
    if (InspectorInstrumentationWebKit::shouldInterceptResponse(m_coreLoader->frame(), response)) {
156
        auto interceptedRequestIdentifier = m_coreLoader->identifier();
156
        auto interceptedRequestIdentifier = m_coreLoader->identifier();
157
        m_interceptController.beginInterceptingResponse(interceptedRequestIdentifier);
157
        m_interceptController.beginInterceptingResponse(interceptedRequestIdentifier);
158
        InspectorInstrumentationWebKit::interceptResponse(m_coreLoader->frame(), response, interceptedRequestIdentifier, [this, protectedThis = Ref { *this }, interceptedRequestIdentifier, policyDecisionCompletionHandler = WTFMove(policyDecisionCompletionHandler)](const ResourceResponse& inspectorResponse, RefPtr<SharedBuffer> overrideData) mutable {
158
        InspectorInstrumentationWebKit::interceptResponse(m_coreLoader->frame(), response, interceptedRequestIdentifier, [this, protectedThis = Ref { *this }, interceptedRequestIdentifier, policyDecisionCompletionHandler = WTFMove(policyDecisionCompletionHandler)](const ResourceResponse& inspectorResponse, RefPtr<FragmentedSharedBuffer> overrideData) mutable {
159
            if (!m_coreLoader || !m_coreLoader->identifier()) {
159
            if (!m_coreLoader || !m_coreLoader->identifier()) {
160
                WEBRESOURCELOADER_RELEASE_LOG("didReceiveResponse: not continuing intercept load because no coreLoader or no ID");
160
                WEBRESOURCELOADER_RELEASE_LOG("didReceiveResponse: not continuing intercept load because no coreLoader or no ID");
161
                m_interceptController.continueResponse(interceptedRequestIdentifier);
161
                m_interceptController.continueResponse(interceptedRequestIdentifier);
Lines 295-305 void WebResourceLoader::didReceiveResource(const ShareableResource::Handle& hand a/Source/WebKit/WebProcess/Network/WebResourceLoader.cpp_sec2
295
    LOG(Network, "(WebProcess) WebResourceLoader::didReceiveResource for '%s'", m_coreLoader->url().string().latin1().data());
295
    LOG(Network, "(WebProcess) WebResourceLoader::didReceiveResource for '%s'", m_coreLoader->url().string().latin1().data());
296
    WEBRESOURCELOADER_RELEASE_LOG("didReceiveResource:");
296
    WEBRESOURCELOADER_RELEASE_LOG("didReceiveResource:");
297
297
298
    RefPtr<SharedBuffer> buffer = handle.tryWrapInSharedBuffer();
298
    RefPtr<FragmentedSharedBuffer> buffer = handle.tryWrapInSharedBuffer();
299
299
300
    if (!buffer) {
300
    if (!buffer) {
301
        LOG_ERROR("Unable to create buffer from ShareableResource sent from the network process.");
301
        LOG_ERROR("Unable to create buffer from ShareableResource sent from the network process.");
302
        WEBRESOURCELOADER_RELEASE_LOG("didReceiveResource: Unable to create SharedBuffer");
302
        WEBRESOURCELOADER_RELEASE_LOG("didReceiveResource: Unable to create FragmentedSharedBuffer");
303
        if (auto* frame = m_coreLoader->frame()) {
303
        if (auto* frame = m_coreLoader->frame()) {
304
            if (auto* page = frame->page())
304
            if (auto* page = frame->page())
305
                page->diagnosticLoggingClient().logDiagnosticMessage(WebCore::DiagnosticLoggingKeys::internalErrorKey(), WebCore::DiagnosticLoggingKeys::createSharedBufferFailedKey(), WebCore::ShouldSample::No);
305
                page->diagnosticLoggingClient().logDiagnosticMessage(WebCore::DiagnosticLoggingKeys::internalErrorKey(), WebCore::DiagnosticLoggingKeys::createSharedBufferFailedKey(), WebCore::ShouldSample::No);
- a/Source/WebKit/WebProcess/Plugins/PDF/PDFPlugin.h -1 / +1 lines
Lines 207-213 private: a/Source/WebKit/WebProcess/Plugins/PDF/PDFPlugin.h_sec1
207
    void privateBrowsingStateChanged(bool) final { }
207
    void privateBrowsingStateChanged(bool) final { }
208
    bool getFormValue(String& formValue) final { return false; }
208
    bool getFormValue(String& formValue) final { return false; }
209
    bool handleScroll(WebCore::ScrollDirection, WebCore::ScrollGranularity) final;
209
    bool handleScroll(WebCore::ScrollDirection, WebCore::ScrollGranularity) final;
210
    RefPtr<WebCore::SharedBuffer> liveResourceData() const final;
210
    RefPtr<WebCore::FragmentedSharedBuffer> liveResourceData() const final;
211
    void willDetachRenderer() final;
211
    void willDetachRenderer() final;
212
    bool pluginHandlesContentOffsetForAccessibilityHitTest() const final;
212
    bool pluginHandlesContentOffsetForAccessibilityHitTest() const final;
213
    
213
    
- a/Source/WebKit/WebProcess/Plugins/PDF/PDFPlugin.mm -1 / +1 lines
Lines 2552-2558 void PDFPlugin::notifyDisplayModeChanged(int) a/Source/WebKit/WebProcess/Plugins/PDF/PDFPlugin.mm_sec1
2552
    updateScrollbars();
2552
    updateScrollbars();
2553
}
2553
}
2554
2554
2555
RefPtr<SharedBuffer> PDFPlugin::liveResourceData() const
2555
RefPtr<FragmentedSharedBuffer> PDFPlugin::liveResourceData() const
2556
{
2556
{
2557
    NSData *pdfData = liveData();
2557
    NSData *pdfData = liveData();
2558
2558
- a/Source/WebKit/WebProcess/Plugins/Plugin.h -2 / +2 lines
Lines 61-67 class IntPoint; a/Source/WebKit/WebProcess/Plugins/Plugin.h_sec1
61
class IntRect;
61
class IntRect;
62
class IntSize;
62
class IntSize;
63
class Scrollbar;
63
class Scrollbar;
64
class SharedBuffer;
64
class FragmentedSharedBuffer;
65
}
65
}
66
66
67
namespace WebKit {
67
namespace WebKit {
Lines 288-294 public: a/Source/WebKit/WebProcess/Plugins/Plugin.h_sec2
288
288
289
    virtual WebCore::IntPoint convertToRootView(const WebCore::IntPoint& pointInLocalCoordinates) const;
289
    virtual WebCore::IntPoint convertToRootView(const WebCore::IntPoint& pointInLocalCoordinates) const;
290
290
291
    virtual RefPtr<WebCore::SharedBuffer> liveResourceData() const = 0;
291
    virtual RefPtr<WebCore::FragmentedSharedBuffer> liveResourceData() const = 0;
292
292
293
    virtual bool performDictionaryLookupAtLocation(const WebCore::FloatPoint&) = 0;
293
    virtual bool performDictionaryLookupAtLocation(const WebCore::FloatPoint&) = 0;
294
294
- a/Source/WebKit/WebProcess/Plugins/PluginView.cpp -10 / +8 lines
Lines 289-294 PluginView::PluginView(HTMLPlugInElement& pluginElement, Ref<Plugin>&& plugin, c a/Source/WebKit/WebProcess/Plugins/PluginView.cpp_sec1
289
    , m_webPage(webPage(m_pluginElement.get()))
289
    , m_webPage(webPage(m_pluginElement.get()))
290
    , m_parameters(parameters)
290
    , m_parameters(parameters)
291
    , m_pendingURLRequestsTimer(RunLoop::main(), this, &PluginView::pendingURLRequestsTimerFired)
291
    , m_pendingURLRequestsTimer(RunLoop::main(), this, &PluginView::pendingURLRequestsTimerFired)
292
    , m_manualStreamData(makeUniqueRef<SharedBufferBuilder>())
292
{
293
{
293
    m_webPage->addPluginView(this);
294
    m_webPage->addPluginView(this);
294
}
295
}
Lines 403-411 void PluginView::manualLoadDidReceiveData(const uint8_t* bytes, int length) a/Source/WebKit/WebProcess/Plugins/PluginView.cpp_sec2
403
404
404
    if (!m_isInitialized) {
405
    if (!m_isInitialized) {
405
        ASSERT(m_manualStreamState == ManualStreamState::HasReceivedResponse);
406
        ASSERT(m_manualStreamState == ManualStreamState::HasReceivedResponse);
406
        if (!m_manualStreamData)
407
            m_manualStreamData = SharedBuffer::create();
408
409
        m_manualStreamData->append(bytes, length);
407
        m_manualStreamData->append(bytes, length);
410
        return;
408
        return;
411
    }
409
    }
Lines 437-443 void PluginView::manualLoadDidFail(const ResourceError& error) a/Source/WebKit/WebProcess/Plugins/PluginView.cpp_sec3
437
    if (!m_isInitialized) {
435
    if (!m_isInitialized) {
438
        m_manualStreamState = ManualStreamState::Finished;
436
        m_manualStreamState = ManualStreamState::Finished;
439
        m_manualStreamError = error;
437
        m_manualStreamError = error;
440
        m_manualStreamData = nullptr;
438
        m_manualStreamData->reset();
441
        return;
439
        return;
442
    }
440
    }
443
441
Lines 926-936 void PluginView::willDetachRenderer() a/Source/WebKit/WebProcess/Plugins/PluginView.cpp_sec4
926
    m_plugin->willDetachRenderer();
924
    m_plugin->willDetachRenderer();
927
}
925
}
928
926
929
RefPtr<SharedBuffer> PluginView::liveResourceData() const
927
RefPtr<FragmentedSharedBuffer> PluginView::liveResourceData() const
930
{
928
{
931
    if (!m_isInitialized || !m_plugin) {
929
    if (!m_isInitialized || !m_plugin) {
932
        if (m_manualStreamData && m_manualStreamState == ManualStreamState::Finished)
930
        if (m_manualStreamState == ManualStreamState::Finished)
933
            return m_manualStreamData;
931
            return m_manualStreamData->get();
934
932
935
        return nullptr;
933
        return nullptr;
936
    }
934
    }
Lines 1242-1251 void PluginView::redeliverManualStream() a/Source/WebKit/WebProcess/Plugins/PluginView.cpp_sec5
1242
    manualLoadDidReceiveResponse(m_manualStreamResponse);
1240
    manualLoadDidReceiveResponse(m_manualStreamResponse);
1243
1241
1244
    // Deliver the data.
1242
    // Deliver the data.
1245
    if (m_manualStreamData) {
1243
    if (!m_manualStreamData->isNull()) {
1246
        for (const auto& element : *m_manualStreamData)
1244
        auto buffer = m_manualStreamData->take();
1245
        for (const auto& element : buffer.get())
1247
            manualLoadDidReceiveData(element.segment->data(), element.segment->size());
1246
            manualLoadDidReceiveData(element.segment->data(), element.segment->size());
1248
        m_manualStreamData = nullptr;
1249
    }
1247
    }
1250
1248
1251
    if (m_manualStreamState == ManualStreamState::Finished)
1249
    if (m_manualStreamState == ManualStreamState::Finished)
- a/Source/WebKit/WebProcess/Plugins/PluginView.h -2 / +3 lines
Lines 41-46 a/Source/WebKit/WebProcess/Plugins/PluginView.h_sec1
41
#include <memory>
41
#include <memory>
42
#include <wtf/Deque.h>
42
#include <wtf/Deque.h>
43
#include <wtf/RunLoop.h>
43
#include <wtf/RunLoop.h>
44
#include <wtf/UniqueRef.h>
44
45
45
// FIXME: Eventually this should move to WebCore.
46
// FIXME: Eventually this should move to WebCore.
46
47
Lines 115-121 public: a/Source/WebKit/WebProcess/Plugins/PluginView.h_sec2
115
116
116
    bool shouldAllowScripting();
117
    bool shouldAllowScripting();
117
118
118
    RefPtr<WebCore::SharedBuffer> liveResourceData() const;
119
    RefPtr<WebCore::FragmentedSharedBuffer> liveResourceData() const;
119
    bool performDictionaryLookupAtLocation(const WebCore::FloatPoint&);
120
    bool performDictionaryLookupAtLocation(const WebCore::FloatPoint&);
120
    String getSelectionForWordAtPoint(const WebCore::FloatPoint&) const;
121
    String getSelectionForWordAtPoint(const WebCore::FloatPoint&) const;
121
    bool existingSelectionContainsPoint(const WebCore::FloatPoint&) const;
122
    bool existingSelectionContainsPoint(const WebCore::FloatPoint&) const;
Lines 252-258 private: a/Source/WebKit/WebProcess/Plugins/PluginView.h_sec3
252
253
253
    WebCore::ResourceResponse m_manualStreamResponse;
254
    WebCore::ResourceResponse m_manualStreamResponse;
254
    WebCore::ResourceError m_manualStreamError;
255
    WebCore::ResourceError m_manualStreamError;
255
    RefPtr<WebCore::SharedBuffer> m_manualStreamData;
256
    UniqueRef<WebCore::SharedBufferBuilder> m_manualStreamData;
256
257
257
    // This snapshot is used to avoid side effects should the plugin run JS during painting.
258
    // This snapshot is used to avoid side effects should the plugin run JS during painting.
258
    RefPtr<ShareableBitmap> m_transientPaintingSnapshot;
259
    RefPtr<ShareableBitmap> m_transientPaintingSnapshot;
- a/Source/WebKit/WebProcess/Storage/WebServiceWorkerFetchTaskClient.cpp -7 / +6 lines
Lines 71-86 void WebServiceWorkerFetchTaskClient::didReceiveResponse(const ResourceResponse& a/Source/WebKit/WebProcess/Storage/WebServiceWorkerFetchTaskClient.cpp_sec1
71
    m_connection->send(Messages::ServiceWorkerFetchTask::DidReceiveResponse { response, m_needsContinueDidReceiveResponseMessage }, m_fetchIdentifier);
71
    m_connection->send(Messages::ServiceWorkerFetchTask::DidReceiveResponse { response, m_needsContinueDidReceiveResponseMessage }, m_fetchIdentifier);
72
}
72
}
73
73
74
void WebServiceWorkerFetchTaskClient::didReceiveData(Ref<SharedBuffer>&& buffer)
74
void WebServiceWorkerFetchTaskClient::didReceiveData(Ref<FragmentedSharedBuffer>&& buffer)
75
{
75
{
76
    if (!m_connection)
76
    if (!m_connection)
77
        return;
77
        return;
78
78
79
    if (m_waitingForContinueDidReceiveResponseMessage) {
79
    if (m_waitingForContinueDidReceiveResponseMessage) {
80
        if (!std::holds_alternative<Ref<SharedBuffer>>(m_responseData))
80
        if (!std::holds_alternative<SharedBufferBuilder>(m_responseData))
81
            m_responseData = buffer->copy();
81
            m_responseData = SharedBufferBuilder();
82
        else
82
        std::get<SharedBufferBuilder>(m_responseData).append(WTFMove(buffer));
83
            std::get<Ref<SharedBuffer>>(m_responseData)->append(WTFMove(buffer));
84
        return;
83
        return;
85
    }
84
    }
86
85
Lines 206-213 void WebServiceWorkerFetchTaskClient::continueDidReceiveResponse() a/Source/WebKit/WebProcess/Storage/WebServiceWorkerFetchTaskClient.cpp_sec2
206
    switchOn(m_responseData, [this](std::nullptr_t&) {
205
    switchOn(m_responseData, [this](std::nullptr_t&) {
207
        if (m_didFinish)
206
        if (m_didFinish)
208
            didFinish();
207
            didFinish();
209
    }, [this](Ref<SharedBuffer>& buffer) {
208
    }, [this](const SharedBufferBuilder& buffer) {
210
        didReceiveData(WTFMove(buffer));
209
        didReceiveData(*buffer.get());
211
        if (m_didFinish)
210
        if (m_didFinish)
212
            didFinish();
211
            didFinish();
213
    }, [this](Ref<FormData>& formData) {
212
    }, [this](Ref<FormData>& formData) {
- a/Source/WebKit/WebProcess/Storage/WebServiceWorkerFetchTaskClient.h -2 / +3 lines
Lines 33-38 a/Source/WebKit/WebProcess/Storage/WebServiceWorkerFetchTaskClient.h_sec1
33
#include <WebCore/FetchLoaderClient.h>
33
#include <WebCore/FetchLoaderClient.h>
34
#include <WebCore/ServiceWorkerFetch.h>
34
#include <WebCore/ServiceWorkerFetch.h>
35
#include <WebCore/ServiceWorkerTypes.h>
35
#include <WebCore/ServiceWorkerTypes.h>
36
#include <WebCore/SharedBuffer.h>
36
#include <wtf/UniqueRef.h>
37
#include <wtf/UniqueRef.h>
37
38
38
namespace WebKit {
39
namespace WebKit {
Lines 49-55 private: a/Source/WebKit/WebProcess/Storage/WebServiceWorkerFetchTaskClient.h_sec2
49
50
50
    void didReceiveResponse(const WebCore::ResourceResponse&) final;
51
    void didReceiveResponse(const WebCore::ResourceResponse&) final;
51
    void didReceiveRedirection(const WebCore::ResourceResponse&) final;
52
    void didReceiveRedirection(const WebCore::ResourceResponse&) final;
52
    void didReceiveData(Ref<WebCore::SharedBuffer>&&) final;
53
    void didReceiveData(Ref<WebCore::FragmentedSharedBuffer>&&) final;
53
    void didReceiveFormDataAndFinish(Ref<WebCore::FormData>&&) final;
54
    void didReceiveFormDataAndFinish(Ref<WebCore::FormData>&&) final;
54
    void didFail(const WebCore::ResourceError&) final;
55
    void didFail(const WebCore::ResourceError&) final;
55
    void didFinish() final;
56
    void didFinish() final;
Lines 82-88 private: a/Source/WebKit/WebProcess/Storage/WebServiceWorkerFetchTaskClient.h_sec3
82
    std::optional<BlobLoader> m_blobLoader;
83
    std::optional<BlobLoader> m_blobLoader;
83
    bool m_needsContinueDidReceiveResponseMessage { false };
84
    bool m_needsContinueDidReceiveResponseMessage { false };
84
    bool m_waitingForContinueDidReceiveResponseMessage { false };
85
    bool m_waitingForContinueDidReceiveResponseMessage { false };
85
    std::variant<std::nullptr_t, Ref<WebCore::SharedBuffer>, Ref<WebCore::FormData>, UniqueRef<WebCore::ResourceError>> m_responseData;
86
    std::variant<std::nullptr_t, WebCore::SharedBufferBuilder, Ref<WebCore::FormData>, UniqueRef<WebCore::ResourceError>> m_responseData;
86
    bool m_didFinish { false };
87
    bool m_didFinish { false };
87
};
88
};
88
89
- a/Source/WebKit/WebProcess/WebCoreSupport/WebEditorClient.cpp -1 / +1 lines
Lines 142-148 bool WebEditorClient::shouldApplyStyle(const StyleProperties& style, const std:: a/Source/WebKit/WebProcess/WebCoreSupport/WebEditorClient.cpp_sec1
142
142
143
#if ENABLE(ATTACHMENT_ELEMENT)
143
#if ENABLE(ATTACHMENT_ELEMENT)
144
144
145
void WebEditorClient::registerAttachmentIdentifier(const String& identifier, const String& contentType, const String& preferredFileName, Ref<SharedBuffer>&& data)
145
void WebEditorClient::registerAttachmentIdentifier(const String& identifier, const String& contentType, const String& preferredFileName, Ref<FragmentedSharedBuffer>&& data)
146
{
146
{
147
    m_page->send(Messages::WebPageProxy::RegisterAttachmentIdentifierFromData(identifier, contentType, preferredFileName, data.get()));
147
    m_page->send(Messages::WebPageProxy::RegisterAttachmentIdentifierFromData(identifier, contentType, preferredFileName, data.get()));
148
}
148
}
- a/Source/WebKit/WebProcess/WebCoreSupport/WebEditorClient.h -1 / +1 lines
Lines 65-71 private: a/Source/WebKit/WebProcess/WebCoreSupport/WebEditorClient.h_sec1
65
    bool shouldMoveRangeAfterDelete(const WebCore::SimpleRange&, const WebCore::SimpleRange&) final;
65
    bool shouldMoveRangeAfterDelete(const WebCore::SimpleRange&, const WebCore::SimpleRange&) final;
66
66
67
#if ENABLE(ATTACHMENT_ELEMENT)
67
#if ENABLE(ATTACHMENT_ELEMENT)
68
    void registerAttachmentIdentifier(const String&, const String& contentType, const String& preferredFileName, Ref<WebCore::SharedBuffer>&&) final;
68
    void registerAttachmentIdentifier(const String&, const String& contentType, const String& preferredFileName, Ref<WebCore::FragmentedSharedBuffer>&&) final;
69
    void registerAttachmentIdentifier(const String&, const String& contentType, const String& filePath) final;
69
    void registerAttachmentIdentifier(const String&, const String& contentType, const String& filePath) final;
70
    void registerAttachmentIdentifier(const String&) final;
70
    void registerAttachmentIdentifier(const String&) final;
71
    void registerAttachments(Vector<WebCore::SerializedAttachmentData>&&) final;
71
    void registerAttachments(Vector<WebCore::SerializedAttachmentData>&&) final;
- a/Source/WebKit/WebProcess/WebCoreSupport/WebFrameLoaderClient.cpp -2 / +2 lines
Lines 1188-1195 void WebFrameLoaderClient::finishedLoading(DocumentLoader* loader) a/Source/WebKit/WebProcess/WebCoreSupport/WebFrameLoaderClient.cpp_sec1
1188
            if (!webPage)
1188
            if (!webPage)
1189
                return;
1189
                return;
1190
1190
1191
            RefPtr<SharedBuffer> mainResourceData = loader->mainResourceData();
1191
            RefPtr<FragmentedSharedBuffer> mainResourceData = loader->mainResourceData();
1192
            IPC::DataReference dataReference(mainResourceData ? mainResourceData->data() : nullptr, mainResourceData ? mainResourceData->size() : 0);
1192
            IPC::DataReference dataReference(mainResourceData ? mainResourceData->makeContiguous()->data() : nullptr, mainResourceData ? mainResourceData->size() : 0);
1193
            webPage->send(Messages::WebPageProxy::DidFinishLoadingDataForCustomContentProvider(loader->response().suggestedFilename(), dataReference));
1193
            webPage->send(Messages::WebPageProxy::DidFinishLoadingDataForCustomContentProvider(loader->response().suggestedFilename(), dataReference));
1194
        }
1194
        }
1195
1195
- a/Source/WebKit/WebProcess/WebCoreSupport/WebPlatformStrategies.cpp -1 / +1 lines
Lines 209-215 int64_t WebPlatformStrategies::setTypes(const Vector<String>& pasteboardTypes, c a/Source/WebKit/WebProcess/WebCoreSupport/WebPlatformStrategies.cpp_sec1
209
    return newChangeCount;
209
    return newChangeCount;
210
}
210
}
211
211
212
int64_t WebPlatformStrategies::setBufferForType(SharedBuffer* buffer, const String& pasteboardType, const String& pasteboardName, const PasteboardContext* context)
212
int64_t WebPlatformStrategies::setBufferForType(FragmentedSharedBuffer* buffer, const String& pasteboardType, const String& pasteboardName, const PasteboardContext* context)
213
{
213
{
214
    SharedMemory::Handle handle;
214
    SharedMemory::Handle handle;
215
    if (buffer && buffer->size()) {
215
    if (buffer && buffer->size()) {
- a/Source/WebKit/WebProcess/WebCoreSupport/WebPlatformStrategies.h -1 / +1 lines
Lines 66-72 private: a/Source/WebKit/WebProcess/WebCoreSupport/WebPlatformStrategies.h_sec1
66
66
67
    int64_t addTypes(const Vector<String>& pasteboardTypes, const String& pasteboardName, const WebCore::PasteboardContext*) override;
67
    int64_t addTypes(const Vector<String>& pasteboardTypes, const String& pasteboardName, const WebCore::PasteboardContext*) override;
68
    int64_t setTypes(const Vector<String>& pasteboardTypes, const String& pasteboardName, const WebCore::PasteboardContext*) override;
68
    int64_t setTypes(const Vector<String>& pasteboardTypes, const String& pasteboardName, const WebCore::PasteboardContext*) override;
69
    int64_t setBufferForType(WebCore::SharedBuffer*, const String& pasteboardType, const String& pasteboardName, const WebCore::PasteboardContext*) override;
69
    int64_t setBufferForType(WebCore::FragmentedSharedBuffer*, const String& pasteboardType, const String& pasteboardName, const WebCore::PasteboardContext*) override;
70
    int64_t setURL(const WebCore::PasteboardURL&, const String& pasteboardName, const WebCore::PasteboardContext*) override;
70
    int64_t setURL(const WebCore::PasteboardURL&, const String& pasteboardName, const WebCore::PasteboardContext*) override;
71
    int64_t setColor(const WebCore::Color&, const String& pasteboardName, const WebCore::PasteboardContext*) override;
71
    int64_t setColor(const WebCore::Color&, const String& pasteboardName, const WebCore::PasteboardContext*) override;
72
    int64_t setStringForType(const String&, const String& pasteboardType, const String& pasteboardName, const WebCore::PasteboardContext*) override;
72
    int64_t setStringForType(const String&, const String& pasteboardType, const String& pasteboardName, const WebCore::PasteboardContext*) override;
- a/Source/WebKit/WebProcess/WebCoreSupport/ios/WebPreviewLoaderClient.cpp -5 / +4 lines
Lines 45-57 WebPreviewLoaderClient::WebPreviewLoaderClient(const String& fileName, const Str a/Source/WebKit/WebProcess/WebCoreSupport/ios/WebPreviewLoaderClient.cpp_sec1
45
    : m_fileName { fileName }
45
    : m_fileName { fileName }
46
    , m_uti { uti }
46
    , m_uti { uti }
47
    , m_pageID { pageID }
47
    , m_pageID { pageID }
48
    , m_buffer { SharedBuffer::create() }
48
    , m_buffer { makeUniqueRef<SharedBufferBuilder>() }
49
{
49
{
50
}
50
}
51
51
52
WebPreviewLoaderClient::~WebPreviewLoaderClient() = default;
52
WebPreviewLoaderClient::~WebPreviewLoaderClient() = default;
53
53
54
void WebPreviewLoaderClient::didReceiveBuffer(const SharedBuffer& buffer)
54
void WebPreviewLoaderClient::didReceiveBuffer(const FragmentedSharedBuffer& buffer)
55
{
55
{
56
    auto webPage = WebProcess::singleton().webPage(m_pageID);
56
    auto webPage = WebProcess::singleton().webPage(m_pageID);
57
    if (!webPage)
57
    if (!webPage)
Lines 69-81 void WebPreviewLoaderClient::didFinishLoading() a/Source/WebKit/WebProcess/WebCoreSupport/ios/WebPreviewLoaderClient.cpp_sec2
69
    if (!webPage)
69
    if (!webPage)
70
        return;
70
        return;
71
71
72
    webPage->didFinishLoadForQuickLookDocumentInMainFrame(m_buffer.get());
72
    webPage->didFinishLoadForQuickLookDocumentInMainFrame(m_buffer->take().get());
73
    m_buffer->clear();
74
}
73
}
75
74
76
void WebPreviewLoaderClient::didFail()
75
void WebPreviewLoaderClient::didFail()
77
{
76
{
78
    m_buffer->clear();
77
    m_buffer->reset();
79
}
78
}
80
79
81
void WebPreviewLoaderClient::didRequestPassword(Function<void(const String&)>&& completionHandler)
80
void WebPreviewLoaderClient::didRequestPassword(Function<void(const String&)>&& completionHandler)
- a/Source/WebKit/WebProcess/WebCoreSupport/ios/WebPreviewLoaderClient.h -2 / +7 lines
Lines 29-36 a/Source/WebKit/WebProcess/WebCoreSupport/ios/WebPreviewLoaderClient.h_sec1
29
29
30
#include <WebCore/LegacyPreviewLoaderClient.h>
30
#include <WebCore/LegacyPreviewLoaderClient.h>
31
#include <WebCore/PageIdentifier.h>
31
#include <WebCore/PageIdentifier.h>
32
#include <wtf/UniqueRef.h>
32
#include <wtf/text/WTFString.h>
33
#include <wtf/text/WTFString.h>
33
34
35
namespace WebCore {
36
class SharedBufferBuilder;
37
}
38
34
namespace WebKit {
39
namespace WebKit {
35
40
36
class WebFrame;
41
class WebFrame;
Lines 45-51 public: a/Source/WebKit/WebProcess/WebCoreSupport/ios/WebPreviewLoaderClient.h_sec2
45
50
46
private:
51
private:
47
    WebPreviewLoaderClient(const String& fileName, const String& uti, WebCore::PageIdentifier);
52
    WebPreviewLoaderClient(const String& fileName, const String& uti, WebCore::PageIdentifier);
48
    void didReceiveBuffer(const WebCore::SharedBuffer&) override;
53
    void didReceiveBuffer(const WebCore::FragmentedSharedBuffer&) override;
49
    void didFinishLoading() override;
54
    void didFinishLoading() override;
50
    void didFail() override;
55
    void didFail() override;
51
    bool supportsPasswordEntry() const override { return true; }
56
    bool supportsPasswordEntry() const override { return true; }
Lines 54-60 private: a/Source/WebKit/WebProcess/WebCoreSupport/ios/WebPreviewLoaderClient.h_sec3
54
    const String m_fileName;
59
    const String m_fileName;
55
    const String m_uti;
60
    const String m_uti;
56
    const WebCore::PageIdentifier m_pageID;
61
    const WebCore::PageIdentifier m_pageID;
57
    Ref<WebCore::SharedBuffer> m_buffer;
62
    UniqueRef<WebCore::SharedBufferBuilder> m_buffer;
58
};
63
};
59
64
60
} // namespace WebKit
65
} // namespace WebKit
- a/Source/WebKit/WebProcess/WebCoreSupport/mac/WebDragClientMac.mm -1 / +1 lines
Lines 150-156 void WebDragClient::declareAndWriteDragImage(const String& pasteboardName, Eleme a/Source/WebKit/WebProcess/WebCoreSupport/mac/WebDragClientMac.mm_sec1
150
150
151
    NSURLResponse *response = image->response().nsURLResponse();
151
    NSURLResponse *response = image->response().nsURLResponse();
152
    
152
    
153
    RefPtr<SharedBuffer> imageBuffer = image->image()->data();
153
    auto imageBuffer = image->image()->data();
154
    size_t imageSize = imageBuffer->size();
154
    size_t imageSize = imageBuffer->size();
155
155
156
    auto sharedMemoryBuffer = SharedMemory::copyBuffer(*imageBuffer);
156
    auto sharedMemoryBuffer = SharedMemory::copyBuffer(*imageBuffer);
- a/Source/WebKit/WebProcess/WebPage/WebFrame.cpp -2 / +2 lines
Lines 340-349 String WebFrame::source() const a/Source/WebKit/WebProcess/WebPage/WebFrame.cpp_sec1
340
    DocumentLoader* documentLoader = m_coreFrame->loader().activeDocumentLoader();
340
    DocumentLoader* documentLoader = m_coreFrame->loader().activeDocumentLoader();
341
    if (!documentLoader)
341
    if (!documentLoader)
342
        return String();
342
        return String();
343
    RefPtr<SharedBuffer> mainResourceData = documentLoader->mainResourceData();
343
    RefPtr<FragmentedSharedBuffer> mainResourceData = documentLoader->mainResourceData();
344
    if (!mainResourceData)
344
    if (!mainResourceData)
345
        return String();
345
        return String();
346
    return decoder->encoding().decode(mainResourceData->data(), mainResourceData->size());
346
    return decoder->encoding().decode(mainResourceData->makeContiguous()->data(), mainResourceData->size());
347
}
347
}
348
348
349
String WebFrame::contentsAsString() const 
349
String WebFrame::contentsAsString() const 
- a/Source/WebKit/WebProcess/WebPage/WebPage.cpp -6 / +6 lines
Lines 1738-1744 NO_RETURN void WebPage::loadRequestWaitingForProcessLaunch(LoadParameters&&, URL a/Source/WebKit/WebProcess/WebPage/WebPage.cpp_sec1
1738
    RELEASE_ASSERT_NOT_REACHED();
1738
    RELEASE_ASSERT_NOT_REACHED();
1739
}
1739
}
1740
1740
1741
void WebPage::loadDataImpl(uint64_t navigationID, ShouldTreatAsContinuingLoad shouldTreatAsContinuingLoad, std::optional<WebsitePoliciesData>&& websitePolicies, Ref<SharedBuffer>&& sharedBuffer, ResourceRequest&& request, ResourceResponse&& response, const URL& unreachableURL, const UserData& userData, std::optional<NavigatingToAppBoundDomain> isNavigatingToAppBoundDomain, SubstituteData::SessionHistoryVisibility sessionHistoryVisibility, ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy)
1741
void WebPage::loadDataImpl(uint64_t navigationID, ShouldTreatAsContinuingLoad shouldTreatAsContinuingLoad, std::optional<WebsitePoliciesData>&& websitePolicies, Ref<FragmentedSharedBuffer>&& sharedBuffer, ResourceRequest&& request, ResourceResponse&& response, const URL& unreachableURL, const UserData& userData, std::optional<NavigatingToAppBoundDomain> isNavigatingToAppBoundDomain, SubstituteData::SessionHistoryVisibility sessionHistoryVisibility, ShouldOpenExternalURLsPolicy shouldOpenExternalURLsPolicy)
1742
{
1742
{
1743
#if ENABLE(APP_BOUND_DOMAINS)
1743
#if ENABLE(APP_BOUND_DOMAINS)
1744
    setIsNavigatingToAppBoundDomain(isNavigatingToAppBoundDomain, &m_mainFrame.get());
1744
    setIsNavigatingToAppBoundDomain(isNavigatingToAppBoundDomain, &m_mainFrame.get());
Lines 1753-1759 void WebPage::loadDataImpl(uint64_t navigationID, ShouldTreatAsContinuingLoad sh a/Source/WebKit/WebProcess/WebPage/WebPage.cpp_sec2
1753
1753
1754
    // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1754
    // Let the InjectedBundle know we are about to start the load, passing the user data from the UIProcess
1755
    // to all the client to set up any needed state.
1755
    // to all the client to set up any needed state.
1756
    m_loaderClient->willLoadDataRequest(*this, request, const_cast<SharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1756
    m_loaderClient->willLoadDataRequest(*this, request, const_cast<FragmentedSharedBuffer*>(substituteData.content()), substituteData.mimeType(), substituteData.textEncoding(), substituteData.failingURL(), WebProcess::singleton().transformHandlesToObjects(userData.object()).get());
1757
1757
1758
    // Initate the load in WebCore.
1758
    // Initate the load in WebCore.
1759
    FrameLoadRequest frameLoadRequest(*m_mainFrame->coreFrame(), request, substituteData);
1759
    FrameLoadRequest frameLoadRequest(*m_mainFrame->coreFrame(), request, substituteData);
Lines 3861-3867 void WebPage::getSourceForFrame(FrameIdentifier frameID, CompletionHandler<void( a/Source/WebKit/WebProcess/WebPage/WebPage.cpp_sec3
3861
3861
3862
void WebPage::getMainResourceDataOfFrame(FrameIdentifier frameID, CompletionHandler<void(const std::optional<IPC::SharedBufferDataReference>&)>&& callback)
3862
void WebPage::getMainResourceDataOfFrame(FrameIdentifier frameID, CompletionHandler<void(const std::optional<IPC::SharedBufferDataReference>&)>&& callback)
3863
{
3863
{
3864
    RefPtr<SharedBuffer> buffer;
3864
    RefPtr<FragmentedSharedBuffer> buffer;
3865
    if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
3865
    if (WebFrame* frame = WebProcess::singleton().webFrame(frameID)) {
3866
        if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
3866
        if (PluginView* pluginView = pluginViewForFrame(frame->coreFrame()))
3867
            buffer = pluginView->liveResourceData();
3867
            buffer = pluginView->liveResourceData();
Lines 3877-3883 void WebPage::getMainResourceDataOfFrame(FrameIdentifier frameID, CompletionHand a/Source/WebKit/WebProcess/WebPage/WebPage.cpp_sec4
3877
    callback(dataReference);
3877
    callback(dataReference);
3878
}
3878
}
3879
3879
3880
static RefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
3880
static RefPtr<FragmentedSharedBuffer> resourceDataForFrame(Frame* frame, const URL& resourceURL)
3881
{
3881
{
3882
    DocumentLoader* loader = frame->loader().documentLoader();
3882
    DocumentLoader* loader = frame->loader().documentLoader();
3883
    if (!loader)
3883
    if (!loader)
Lines 3892-3898 static RefPtr<SharedBuffer> resourceDataForFrame(Frame* frame, const URL& resour a/Source/WebKit/WebProcess/WebPage/WebPage.cpp_sec5
3892
3892
3893
void WebPage::getResourceDataFromFrame(FrameIdentifier frameID, const String& resourceURLString, CompletionHandler<void(const std::optional<IPC::SharedBufferDataReference>&)>&& callback)
3893
void WebPage::getResourceDataFromFrame(FrameIdentifier frameID, const String& resourceURLString, CompletionHandler<void(const std::optional<IPC::SharedBufferDataReference>&)>&& callback)
3894
{
3894
{
3895
    RefPtr<SharedBuffer> buffer;
3895
    RefPtr<FragmentedSharedBuffer> buffer;
3896
    if (auto* frame = WebProcess::singleton().webFrame(frameID)) {
3896
    if (auto* frame = WebProcess::singleton().webFrame(frameID)) {
3897
        URL resourceURL(URL(), resourceURLString);
3897
        URL resourceURL(URL(), resourceURLString);
3898
        buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
3898
        buffer = resourceDataForFrame(frame->coreFrame(), resourceURL);
Lines 6977-6983 void WebPage::didGetLoadDecisionForIcon(bool decision, CallbackID loadIdentifier a/Source/WebKit/WebProcess/WebPage/WebPage.cpp_sec6
6977
    if (!documentLoader)
6977
    if (!documentLoader)
6978
        return completionHandler({ });
6978
        return completionHandler({ });
6979
6979
6980
    documentLoader->didGetLoadDecisionForIcon(decision, loadIdentifier.toInteger(), [completionHandler = WTFMove(completionHandler)] (WebCore::SharedBuffer* iconData) mutable {
6980
    documentLoader->didGetLoadDecisionForIcon(decision, loadIdentifier.toInteger(), [completionHandler = WTFMove(completionHandler)] (WebCore::FragmentedSharedBuffer* iconData) mutable {
6981
        completionHandler({ iconData });
6981
        completionHandler({ iconData });
6982
    });
6982
    });
6983
}
6983
}
- a/Source/WebKit/WebProcess/WebPage/WebPage.h -3 / +3 lines
Lines 216-222 class ResourceRequest; a/Source/WebKit/WebProcess/WebPage/WebPage.h_sec1
216
class ResourceResponse;
216
class ResourceResponse;
217
class SelectionData;
217
class SelectionData;
218
class SelectionGeometry;
218
class SelectionGeometry;
219
class SharedBuffer;
219
class FragmentedSharedBuffer;
220
class SubstituteData;
220
class SubstituteData;
221
class TextCheckingRequest;
221
class TextCheckingRequest;
222
class VisiblePosition;
222
class VisiblePosition;
Lines 1396-1402 public: a/Source/WebKit/WebProcess/WebPage/WebPage.h_sec2
1396
1396
1397
#if USE(QUICK_LOOK)
1397
#if USE(QUICK_LOOK)
1398
    void didStartLoadForQuickLookDocumentInMainFrame(const String& fileName, const String& uti);
1398
    void didStartLoadForQuickLookDocumentInMainFrame(const String& fileName, const String& uti);
1399
    void didFinishLoadForQuickLookDocumentInMainFrame(const WebCore::SharedBuffer&);
1399
    void didFinishLoadForQuickLookDocumentInMainFrame(const WebCore::FragmentedSharedBuffer&);
1400
    void requestPasswordForQuickLookDocumentInMainFrame(const String& fileName, CompletionHandler<void(const String&)>&&);
1400
    void requestPasswordForQuickLookDocumentInMainFrame(const String& fileName, CompletionHandler<void(const String&)>&&);
1401
#endif
1401
#endif
1402
1402
Lines 1599-1605 private: a/Source/WebKit/WebProcess/WebPage/WebPage.h_sec3
1599
1599
1600
    String sourceForFrame(WebFrame*);
1600
    String sourceForFrame(WebFrame*);
1601
1601
1602
    void loadDataImpl(uint64_t navigationID, WebCore::ShouldTreatAsContinuingLoad, std::optional<WebsitePoliciesData>&&, Ref<WebCore::SharedBuffer>&&, WebCore::ResourceRequest&&, WebCore::ResourceResponse&&, const URL& failingURL, const UserData&, std::optional<NavigatingToAppBoundDomain>, WebCore::SubstituteData::SessionHistoryVisibility, WebCore::ShouldOpenExternalURLsPolicy = WebCore::ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1602
    void loadDataImpl(uint64_t navigationID, WebCore::ShouldTreatAsContinuingLoad, std::optional<WebsitePoliciesData>&&, Ref<WebCore::FragmentedSharedBuffer>&&, WebCore::ResourceRequest&&, WebCore::ResourceResponse&&, const URL& failingURL, const UserData&, std::optional<NavigatingToAppBoundDomain>, WebCore::SubstituteData::SessionHistoryVisibility, WebCore::ShouldOpenExternalURLsPolicy = WebCore::ShouldOpenExternalURLsPolicy::ShouldNotAllow);
1603
1603
1604
    // Actions
1604
    // Actions
1605
    void tryClose(CompletionHandler<void(bool)>&&);
1605
    void tryClose(CompletionHandler<void(bool)>&&);
- a/Source/WebKit/WebProcess/WebPage/ios/WebPageIOS.mm -2 / +2 lines
Lines 3217-3223 void WebPage::performActionOnElement(uint32_t action) a/Source/WebKit/WebProcess/WebPage/ios/WebPageIOS.mm_sec1
3217
        CachedImage* cachedImage = downcast<RenderImage>(*element.renderer()).cachedImage();
3217
        CachedImage* cachedImage = downcast<RenderImage>(*element.renderer()).cachedImage();
3218
        if (!cachedImage)
3218
        if (!cachedImage)
3219
            return;
3219
            return;
3220
        RefPtr<SharedBuffer> buffer = cachedImage->resourceBuffer();
3220
        RefPtr<FragmentedSharedBuffer> buffer = cachedImage->resourceBuffer();
3221
        if (!buffer)
3221
        if (!buffer)
3222
            return;
3222
            return;
3223
        auto sharedMemoryBuffer = SharedMemory::copyBuffer(*buffer);
3223
        auto sharedMemoryBuffer = SharedMemory::copyBuffer(*buffer);
Lines 4683-4689 void WebPage::didStartLoadForQuickLookDocumentInMainFrame(const String& fileName a/Source/WebKit/WebProcess/WebPage/ios/WebPageIOS.mm_sec2
4683
    send(Messages::WebPageProxy::DidStartLoadForQuickLookDocumentInMainFrame(fileName, uti));
4683
    send(Messages::WebPageProxy::DidStartLoadForQuickLookDocumentInMainFrame(fileName, uti));
4684
}
4684
}
4685
4685
4686
void WebPage::didFinishLoadForQuickLookDocumentInMainFrame(const SharedBuffer& buffer)
4686
void WebPage::didFinishLoadForQuickLookDocumentInMainFrame(const FragmentedSharedBuffer& buffer)
4687
{
4687
{
4688
    ASSERT(!buffer.isEmpty());
4688
    ASSERT(!buffer.isEmpty());
4689
4689
- a/Source/WebKit/WebProcess/WebPage/mac/WebPageMac.mm -1 / +1 lines
Lines 566-572 void WebPage::getDataSelectionForPasteboard(const String pasteboardType, Complet a/Source/WebKit/WebProcess/WebPage/mac/WebPageMac.mm_sec1
566
    if (frame.selection().isNone())
566
    if (frame.selection().isNone())
567
        return completionHandler({ });
567
        return completionHandler({ });
568
568
569
    RefPtr<SharedBuffer> buffer = frame.editor().dataSelectionForPasteboard(pasteboardType);
569
    auto buffer = frame.editor().dataSelectionForPasteboard(pasteboardType);
570
    if (!buffer)
570
    if (!buffer)
571
        return completionHandler({ });
571
        return completionHandler({ });
572
    auto sharedMemoryBuffer = SharedMemory::copyBuffer(*buffer);
572
    auto sharedMemoryBuffer = SharedMemory::copyBuffer(*buffer);
- a/Source/WebKit/WebProcess/win/WebProcessWin.cpp -1 / +1 lines
Lines 28-34 a/Source/WebKit/WebProcess/win/WebProcessWin.cpp_sec1
28
28
29
#include <WebCore/SharedBuffer.h>
29
#include <WebCore/SharedBuffer.h>
30
30
31
RefPtr<WebCore::SharedBuffer> loadResourceIntoBuffer(const char* name)
31
RefPtr<WebCore::FragmentedSharedBuffer> loadResourceIntoBuffer(const char* name)
32
{
32
{
33
    return 0;
33
    return 0;
34
}
34
}
- a/Source/WebKitLegacy/ChangeLog +14 lines
Lines 1-3 a/Source/WebKitLegacy/ChangeLog_sec1
1
2021-12-03  Jean-Yves Avenard  <jya@apple.com>
2
3
        Rename SharedBuffer classes.
4
        https://bugs.webkit.org/show_bug.cgi?id=233677
5
        rdar://problem/85963900
6
7
        Reviewed by NOBODY (OOPS!).
8
9
        SharedBuffer are renamed FragmentedSharedBuffer and
10
        ContiguousSharedBuffer to SharedBuffer to better reflect their actual
11
        types.
12
13
        * WebCoreSupport/PingHandle.h:
14
1
2021-11-12  Darin Adler  <darin@apple.com>
15
2021-11-12  Darin Adler  <darin@apple.com>
2
16
3
        Make sort-Xcode-project-file idempotent
17
        Make sort-Xcode-project-file idempotent
- a/Source/WebKitLegacy/WebCoreSupport/PingHandle.h -1 / +1 lines
Lines 73-79 private: a/Source/WebKitLegacy/WebCoreSupport/PingHandle.h_sec1
73
        completionHandler();
73
        completionHandler();
74
        pingLoadComplete({ }, response);
74
        pingLoadComplete({ }, response);
75
    }
75
    }
76
    void didReceiveBuffer(WebCore::ResourceHandle*, Ref<WebCore::SharedBuffer>&&, int) final { pingLoadComplete(); }
76
    void didReceiveBuffer(WebCore::ResourceHandle*, Ref<WebCore::FragmentedSharedBuffer>&&, int) final { pingLoadComplete(); }
77
    void didFinishLoading(WebCore::ResourceHandle*, const WebCore::NetworkLoadMetrics&) final { pingLoadComplete(); }
77
    void didFinishLoading(WebCore::ResourceHandle*, const WebCore::NetworkLoadMetrics&) final { pingLoadComplete(); }
78
    void didFail(WebCore::ResourceHandle*, const WebCore::ResourceError& error) final { pingLoadComplete(error); }
78
    void didFail(WebCore::ResourceHandle*, const WebCore::ResourceError& error) final { pingLoadComplete(error); }
79
    bool shouldUseCredentialStorage(WebCore::ResourceHandle*) final { return m_shouldUseCredentialStorage; }
79
    bool shouldUseCredentialStorage(WebCore::ResourceHandle*) final { return m_shouldUseCredentialStorage; }
- a/Source/WebKitLegacy/mac/ChangeLog +50 lines
Lines 1-3 a/Source/WebKitLegacy/mac/ChangeLog_sec1
1
2021-12-03  Jean-Yves Avenard  <jya@apple.com>
2
3
        Rename SharedBuffer classes.
4
        https://bugs.webkit.org/show_bug.cgi?id=233677
5
        rdar://problem/85963900
6
7
        Reviewed by NOBODY (OOPS!).
8
9
        SharedBuffer are renamed FragmentedSharedBuffer and
10
        ContiguousSharedBuffer to SharedBuffer to better reflect their actual
11
        types.
12
13
        * WebCoreSupport/WebEditorClient.h:
14
        * WebCoreSupport/WebEditorClient.mm:
15
        * WebCoreSupport/WebFrameLoaderClient.h:
16
        * WebCoreSupport/WebFrameLoaderClient.mm:
17
        * WebCoreSupport/WebPlatformStrategies.h:
18
        * WebCoreSupport/WebPlatformStrategies.mm:
19
        * WebView/WebDataSource.mm:
20
        * WebView/WebHTMLView.mm:
21
        * WebView/WebResource.mm:
22
23
2021-11-25  Jean-Yves Avenard  <jya@apple.com>
24
25
        Distinguish contiguous SharedBuffer from non-contiguous one and guarantee immutability
26
        https://bugs.webkit.org/show_bug.cgi?id=233030
27
        rdar://85333814
28
29
        Reviewed by Darin Adler.
30
31
        * DOM/DOMUIKitExtensions.mm:
32
        (-[DOMHTMLImageElement dataRepresentation:]):
33
        * WebCoreSupport/WebEditorClient.h:
34
        * WebCoreSupport/WebEditorClient.mm:
35
        (WebEditorClient::getClientPasteboardData):
36
        * WebCoreSupport/WebPlatformStrategies.h:
37
        * WebCoreSupport/WebPlatformStrategies.mm:
38
        (WebPlatformStrategies::bufferForType):
39
        (WebPlatformStrategies::readBufferFromPasteboard):
40
        * WebView/WebDataSource.mm:
41
        (-[WebDataSource data]):
42
        * WebView/WebHTMLRepresentation.mm:
43
        (-[WebHTMLRepresentation documentSource]):
44
        * WebView/WebHTMLView.mm:
45
        (createShareMenuItem):
46
        * WebView/WebResource.mm:
47
        (-[WebResource encodeWithCoder:]):
48
        (-[WebResource data]):
49
        (-[WebResource _stringValue]):
50
1
2021-12-02  Myles C. Maxfield  <mmaxfield@apple.com>
51
2021-12-02  Myles C. Maxfield  <mmaxfield@apple.com>
2
52
3
        [WebGPU] Hook up navigator.gpu.requestAdapter()
53
        [WebGPU] Hook up navigator.gpu.requestAdapter()
- a/Source/WebKitLegacy/mac/DOM/DOMUIKitExtensions.mm -1 / +1 lines
Lines 388-394 - (NSData *)dataRepresentation:(BOOL)rawImageData a/Source/WebKitLegacy/mac/DOM/DOMUIKitExtensions.mm_sec1
388
    auto* data = rawImageData ? cachedImage->resourceBuffer() : image->data();
388
    auto* data = rawImageData ? cachedImage->resourceBuffer() : image->data();
389
    if (!data)
389
    if (!data)
390
        return nil;
390
        return nil;
391
    return data->createNSData().autorelease();
391
    return data->makeContiguous()->createNSData().autorelease();
392
}
392
}
393
393
394
- (NSString *)mimeType
394
- (NSString *)mimeType
- a/Source/WebKitLegacy/mac/WebCoreSupport/WebFrameLoaderClient.h -1 / +1 lines
Lines 248-254 private: a/Source/WebKitLegacy/mac/WebCoreSupport/WebFrameLoaderClient.h_sec1
248
    void sendH2Ping(const URL&, CompletionHandler<void(Expected<Seconds, WebCore::ResourceError>&&)>&&) final;
248
    void sendH2Ping(const URL&, CompletionHandler<void(Expected<Seconds, WebCore::ResourceError>&&)>&&) final;
249
249
250
    void getLoadDecisionForIcons(const Vector<std::pair<WebCore::LinkIcon&, uint64_t>>&) final;
250
    void getLoadDecisionForIcons(const Vector<std::pair<WebCore::LinkIcon&, uint64_t>>&) final;
251
    void finishedLoadingIcon(WebCore::SharedBuffer*);
251
    void finishedLoadingIcon(WebCore::FragmentedSharedBuffer*);
252
252
253
#if !PLATFORM(IOS_FAMILY)
253
#if !PLATFORM(IOS_FAMILY)
254
    bool m_loadingIcon { false };
254
    bool m_loadingIcon { false };
- a/Source/WebKitLegacy/mac/WebCoreSupport/WebFrameLoaderClient.mm -3 / +3 lines
Lines 2012-2018 RefPtr<WebCore::LegacyPreviewLoaderClient> WebFrameLoaderClient::createPreviewLo a/Source/WebKitLegacy/mac/WebCoreSupport/WebFrameLoaderClient.mm_sec1
2012
        RetainPtr<NSString> m_filePath;
2012
        RetainPtr<NSString> m_filePath;
2013
        RetainPtr<NSFileHandle> m_fileHandle;
2013
        RetainPtr<NSFileHandle> m_fileHandle;
2014
2014
2015
        void didReceiveBuffer(const WebCore::SharedBuffer& buffer) override
2015
        void didReceiveBuffer(const WebCore::FragmentedSharedBuffer& buffer) override
2016
        {
2016
        {
2017
            auto dataArray = buffer.createNSDataArray();
2017
            auto dataArray = buffer.createNSDataArray();
2018
            for (NSData *data in dataArray.get())
2018
            for (NSData *data in dataArray.get())
Lines 2094-2100 void WebFrameLoaderClient::getLoadDecisionForIcons(const Vector<std::pair<WebCor a/Source/WebKitLegacy/mac/WebCoreSupport/WebFrameLoaderClient.mm_sec2
2094
        }
2094
        }
2095
2095
2096
        m_loadingIcon = true;
2096
        m_loadingIcon = true;
2097
        documentLoader->didGetLoadDecisionForIcon(true, icon->second, [this, weakThis = WeakPtr { *this }] (WebCore::SharedBuffer* buffer) {
2097
        documentLoader->didGetLoadDecisionForIcon(true, icon->second, [this, weakThis = WeakPtr { *this }] (WebCore::FragmentedSharedBuffer* buffer) {
2098
            if (!weakThis)
2098
            if (!weakThis)
2099
                return;
2099
                return;
2100
            finishedLoadingIcon(buffer);
2100
            finishedLoadingIcon(buffer);
Lines 2131-2137 static NSImage *webGetNSImage(WebCore::Image* image, NSSize size) a/Source/WebKitLegacy/mac/WebCoreSupport/WebFrameLoaderClient.mm_sec3
2131
}
2131
}
2132
#endif // !PLATFORM(IOS_FAMILY)
2132
#endif // !PLATFORM(IOS_FAMILY)
2133
2133
2134
void WebFrameLoaderClient::finishedLoadingIcon(WebCore::SharedBuffer* iconData)
2134
void WebFrameLoaderClient::finishedLoadingIcon(WebCore::FragmentedSharedBuffer* iconData)
2135
{
2135
{
2136
#if !PLATFORM(IOS_FAMILY)
2136
#if !PLATFORM(IOS_FAMILY)
2137
    ASSERT(m_loadingIcon);
2137
    ASSERT(m_loadingIcon);
- a/Source/WebKitLegacy/mac/WebCoreSupport/WebPlatformStrategies.h -1 / +1 lines
Lines 75-81 private: a/Source/WebKitLegacy/mac/WebCoreSupport/WebPlatformStrategies.h_sec1
75
75
76
    int64_t addTypes(const Vector<String>& pasteboardTypes, const String& pasteboardName, const WebCore::PasteboardContext*) override;
76
    int64_t addTypes(const Vector<String>& pasteboardTypes, const String& pasteboardName, const WebCore::PasteboardContext*) override;
77
    int64_t setTypes(const Vector<String>& pasteboardTypes, const String& pasteboardName, const WebCore::PasteboardContext*) override;
77
    int64_t setTypes(const Vector<String>& pasteboardTypes, const String& pasteboardName, const WebCore::PasteboardContext*) override;
78
    int64_t setBufferForType(WebCore::SharedBuffer*, const String& pasteboardType, const String& pasteboardName, const WebCore::PasteboardContext*) override;
78
    int64_t setBufferForType(WebCore::FragmentedSharedBuffer*, const String& pasteboardType, const String& pasteboardName, const WebCore::PasteboardContext*) override;
79
    int64_t setURL(const WebCore::PasteboardURL&, const String& pasteboardName, const WebCore::PasteboardContext*) override;
79
    int64_t setURL(const WebCore::PasteboardURL&, const String& pasteboardName, const WebCore::PasteboardContext*) override;
80
    int64_t setColor(const WebCore::Color&, const String& pasteboardName, const WebCore::PasteboardContext*) override;
80
    int64_t setColor(const WebCore::Color&, const String& pasteboardName, const WebCore::PasteboardContext*) override;
81
    int64_t setStringForType(const String&, const String& pasteboardType, const String& pasteboardName, const WebCore::PasteboardContext*) override;
81
    int64_t setStringForType(const String&, const String& pasteboardType, const String& pasteboardName, const WebCore::PasteboardContext*) override;
- a/Source/WebKitLegacy/mac/WebCoreSupport/WebPlatformStrategies.mm -1 / +1 lines
Lines 154-160 int64_t WebPlatformStrategies::setTypes(const Vector<String>& pasteboardTypes, c a/Source/WebKitLegacy/mac/WebCoreSupport/WebPlatformStrategies.mm_sec1
154
    return PlatformPasteboard(pasteboardName).setTypes(pasteboardTypes);
154
    return PlatformPasteboard(pasteboardName).setTypes(pasteboardTypes);
155
}
155
}
156
156
157
int64_t WebPlatformStrategies::setBufferForType(SharedBuffer* buffer, const String& pasteboardType, const String& pasteboardName, const PasteboardContext*)
157
int64_t WebPlatformStrategies::setBufferForType(FragmentedSharedBuffer* buffer, const String& pasteboardType, const String& pasteboardName, const PasteboardContext*)
158
{
158
{
159
    return PlatformPasteboard(pasteboardName).setBufferForType(buffer, pasteboardType);
159
    return PlatformPasteboard(pasteboardName).setBufferForType(buffer, pasteboardType);
160
}
160
}
- a/Source/WebKitLegacy/mac/WebView/WebDataSource.mm -2 / +2 lines
Lines 460-469 - (void)dealloc a/Source/WebKitLegacy/mac/WebView/WebDataSource.mm_sec1
460
460
461
- (NSData *)data
461
- (NSData *)data
462
{
462
{
463
    RefPtr<WebCore::SharedBuffer> mainResourceData = toPrivate(_private)->loader->mainResourceData();
463
    RefPtr<WebCore::FragmentedSharedBuffer> mainResourceData = toPrivate(_private)->loader->mainResourceData();
464
    if (!mainResourceData)
464
    if (!mainResourceData)
465
        return nil;
465
        return nil;
466
    return mainResourceData->createNSData().autorelease();
466
    return mainResourceData->makeContiguous()->createNSData().autorelease();
467
}
467
}
468
468
469
- (id <WebDocumentRepresentation>)representation
469
- (id <WebDocumentRepresentation>)representation
- a/Source/WebKitLegacy/mac/WebView/WebHTMLRepresentation.mm -1 / +1 lines
Lines 230-236 - (BOOL)canSaveAsWebArchive a/Source/WebKitLegacy/mac/WebView/WebHTMLRepresentation.mm_sec1
230
- (NSString *)documentSource
230
- (NSString *)documentSource
231
{
231
{
232
    if ([self _isDisplayingWebArchive]) {            
232
    if ([self _isDisplayingWebArchive]) {            
233
        SharedBuffer *parsedArchiveData = [_private->dataSource _documentLoader]->parsedArchiveData();
233
        auto *parsedArchiveData = [_private->dataSource _documentLoader]->parsedArchiveData();
234
        return adoptNS([[NSString alloc] initWithData:parsedArchiveData ? parsedArchiveData->createNSData().get() : nil encoding:NSUTF8StringEncoding]).autorelease();
234
        return adoptNS([[NSString alloc] initWithData:parsedArchiveData ? parsedArchiveData->createNSData().get() : nil encoding:NSUTF8StringEncoding]).autorelease();
235
    }
235
    }
236
236
- a/Source/WebKitLegacy/mac/WebView/WebHTMLView.mm -2 / +2 lines
Lines 3540-3547 static RetainPtr<NSMenuItem> createShareMenuItem(const WebCore::HitTestResult& h a/Source/WebKitLegacy/mac/WebView/WebHTMLView.mm_sec1
3540
    }
3540
    }
3541
3541
3542
    if (auto* image = hitTestResult.image()) {
3542
    if (auto* image = hitTestResult.image()) {
3543
        if (RefPtr<WebCore::SharedBuffer> buffer = image->data())
3543
        if (RefPtr<WebCore::FragmentedSharedBuffer> buffer = image->data())
3544
            [items addObject:adoptNS([[NSImage alloc] initWithData:[NSData dataWithBytes:buffer->data() length:buffer->size()]]).get()];
3544
            [items addObject:adoptNS([[NSImage alloc] initWithData:[NSData dataWithBytes:buffer->makeContiguous()->data() length:buffer->size()]]).get()];
3545
    }
3545
    }
3546
3546
3547
    if (!hitTestResult.selectedText().isEmpty()) {
3547
    if (!hitTestResult.selectedText().isEmpty()) {
- a/Source/WebKitLegacy/mac/WebView/WebResource.mm -8 / +8 lines
Lines 163-183 - (instancetype)initWithCoder:(NSCoder *)decoder a/Source/WebKitLegacy/mac/WebView/WebResource.mm_sec1
163
- (void)encodeWithCoder:(NSCoder *)encoder
163
- (void)encodeWithCoder:(NSCoder *)encoder
164
{
164
{
165
    auto* resource = _private->coreResource.get();
165
    auto* resource = _private->coreResource.get();
166
    
166
167
    NSData *data = nil;
167
    RetainPtr<NSData> data;
168
    NSURL *url = nil;
168
    NSURL *url = nil;
169
    NSString *mimeType = nil, *textEncoding = nil, *frameName = nil;
169
    NSString *mimeType = nil, *textEncoding = nil, *frameName = nil;
170
    NSURLResponse *response = nil;
170
    NSURLResponse *response = nil;
171
    
171
172
    if (resource) {
172
    if (resource) {
173
        data = resource->data().createNSData().get();
173
        data = resource->data().makeContiguous()->createNSData();
174
        url = resource->url();
174
        url = resource->url();
175
        mimeType = resource->mimeType();
175
        mimeType = resource->mimeType();
176
        textEncoding = resource->textEncoding();
176
        textEncoding = resource->textEncoding();
177
        frameName = resource->frameName();
177
        frameName = resource->frameName();
178
        response = resource->response().nsURLResponse();
178
        response = resource->response().nsURLResponse();
179
    }
179
    }
180
    [encoder encodeObject:data forKey:WebResourceDataKey];
180
    [encoder encodeObject:data.get() forKey:WebResourceDataKey];
181
    [encoder encodeObject:url forKey:WebResourceURLKey];
181
    [encoder encodeObject:url forKey:WebResourceURLKey];
182
    [encoder encodeObject:mimeType forKey:WebResourceMIMETypeKey];
182
    [encoder encodeObject:mimeType forKey:WebResourceMIMETypeKey];
183
    [encoder encodeObject:textEncoding forKey:WebResourceTextEncodingNameKey];
183
    [encoder encodeObject:textEncoding forKey:WebResourceTextEncodingNameKey];
Lines 202-208 - (NSData *)data a/Source/WebKitLegacy/mac/WebView/WebResource.mm_sec2
202
202
203
    if (!_private->coreResource)
203
    if (!_private->coreResource)
204
        return nil;
204
        return nil;
205
    return _private->coreResource->data().createNSData().autorelease();
205
    return _private->coreResource->data().makeContiguous()->createNSData().autorelease();
206
}
206
}
207
207
208
- (NSURL *)URL
208
- (NSURL *)URL
Lines 367-374 - (NSString *)_stringValue a/Source/WebKitLegacy/mac/WebView/WebResource.mm_sec3
367
    if (!encoding.isValid())
367
    if (!encoding.isValid())
368
        encoding = WindowsLatin1Encoding();
368
        encoding = WindowsLatin1Encoding();
369
    
369
    
370
    SharedBuffer* coreData = _private->coreResource ? &_private->coreResource->data() : nullptr;
370
    FragmentedSharedBuffer* coreData = _private->coreResource ? &_private->coreResource->data() : nullptr;
371
    return encoding.decode(reinterpret_cast<const char*>(coreData ? coreData->data() : nullptr), coreData ? coreData->size() : 0);
371
    return encoding.decode(reinterpret_cast<const char*>(coreData ? coreData->makeContiguous()->data() : nullptr), coreData ? coreData->size() : 0);
372
}
372
}
373
373
374
@end
374
@end
- a/Source/WebKitLegacy/win/ChangeLog +57 lines
Lines 1-3 a/Source/WebKitLegacy/win/ChangeLog_sec1
1
2021-12-03  Jean-Yves Avenard  <jya@apple.com>
2
3
        Rename SharedBuffer classes.
4
        https://bugs.webkit.org/show_bug.cgi?id=233677
5
        rdar://problem/85963900
6
7
        Reviewed by NOBODY (OOPS!).
8
9
        SharedBuffer are renamed FragmentedSharedBuffer and
10
        ContiguousSharedBuffer to SharedBuffer to better reflect their actual
11
        types.
12
13
        * MemoryStream.cpp:
14
        * MemoryStream.h:
15
        * WebArchive.cpp:
16
        * WebCoreSupport/WebEditorClient.cpp:
17
        * WebCoreSupport/WebEditorClient.h:
18
        * WebFrame.cpp:
19
        * WebFrame.h:
20
        * WebKitDLL.cpp:
21
        * WebResource.cpp:
22
        * WebResource.h:
23
24
2021-12-01  Jean-Yves Avenard  <jya@apple.com>
25
26
        Add SharedBufferBuilder class
27
        https://bugs.webkit.org/show_bug.cgi?id=233442
28
        rdar://85693939
29
30
        Reviewed by NOBODY (OOPS!).
31
32
        * WebFrame.cpp:
33
        (WebFrame::loadData):
34
35
2021-11-25  Jean-Yves Avenard  <jya@apple.com>
36
37
        Distinguish contiguous SharedBuffer from non-contiguous one and guarantee immutability
38
        https://bugs.webkit.org/show_bug.cgi?id=233030
39
        rdar://85333814
40
41
        Reviewed by Darin Adler.
42
43
        * MemoryStream.cpp:
44
        (MemoryStream::MemoryStream):
45
        (MemoryStream::createInstance):
46
        * MemoryStream.h:
47
        * WebArchive.cpp:
48
        (WebArchive::data):
49
        * WebCoreSupport/WebEditorClient.cpp:
50
        (WebEditorClient::getClientPasteboardData):
51
        * WebCoreSupport/WebEditorClient.h:
52
        * WebDataSource.cpp:
53
        (WebDataSource::data):
54
        * WebResource.cpp:
55
        (WebResource::createInstance):
56
        * WebResource.h:
57
1
2021-12-02  Chris Dumez  <cdumez@apple.com>
58
2021-12-02  Chris Dumez  <cdumez@apple.com>
2
59
3
        [WK2] Make Web Lock API work across multiple WebProcesses
60
        [WK2] Make Web Lock API work across multiple WebProcesses
- a/Source/WebKitLegacy/win/WebDataSource.cpp -1 / +1 lines
Lines 175-181 HRESULT WebDataSource::data(_COM_Outptr_opt_ IStream** stream) a/Source/WebKitLegacy/win/WebDataSource.cpp_sec1
175
    if (!m_loader)
175
    if (!m_loader)
176
        return E_UNEXPECTED;
176
        return E_UNEXPECTED;
177
177
178
    return MemoryStream::createInstance(m_loader->mainResourceData()).copyRefTo(stream);
178
    return MemoryStream::createInstance(m_loader->mainResourceData()->makeContiguous()).copyRefTo(stream);
179
}
179
}
180
180
181
HRESULT WebDataSource::representation(_COM_Outptr_opt_ IWebDocumentRepresentation** rep)
181
HRESULT WebDataSource::representation(_COM_Outptr_opt_ IWebDocumentRepresentation** rep)
- a/Source/WebKitLegacy/win/WebFrame.cpp -5 / +5 lines
Lines 559-565 HRESULT WebFrame::loadRequest(_In_opt_ IWebURLRequest* request) a/Source/WebKitLegacy/win/WebFrame.cpp_sec1
559
    return S_OK;
559
    return S_OK;
560
}
560
}
561
561
562
void WebFrame::loadData(Ref<WebCore::SharedBuffer>&& data, BSTR mimeType, BSTR textEncodingName, BSTR baseURL, BSTR failingURL)
562
void WebFrame::loadData(Ref<WebCore::FragmentedSharedBuffer>&& data, BSTR mimeType, BSTR textEncodingName, BSTR baseURL, BSTR failingURL)
563
{
563
{
564
    String mimeTypeString(mimeType, SysStringLen(mimeType));
564
    String mimeTypeString(mimeType, SysStringLen(mimeType));
565
    if (!mimeType)
565
    if (!mimeType)
Lines 585-605 void WebFrame::loadData(Ref<WebCore::SharedBuffer>&& data, BSTR mimeType, BSTR t a/Source/WebKitLegacy/win/WebFrame.cpp_sec2
585
585
586
HRESULT WebFrame::loadData(_In_opt_ IStream* data, _In_ BSTR mimeType, _In_ BSTR textEncodingName, _In_ BSTR url)
586
HRESULT WebFrame::loadData(_In_opt_ IStream* data, _In_ BSTR mimeType, _In_ BSTR textEncodingName, _In_ BSTR url)
587
{
587
{
588
    auto sharedBuffer = SharedBuffer::create();
588
    SharedBufferBuilder sharedBuffer;
589
589
590
    STATSTG stat;
590
    STATSTG stat;
591
    if (SUCCEEDED(data->Stat(&stat, STATFLAG_NONAME))) {
591
    if (SUCCEEDED(data->Stat(&stat, STATFLAG_NONAME))) {
592
        if (!stat.cbSize.HighPart && stat.cbSize.LowPart) {
592
        if (!stat.cbSize.HighPart && stat.cbSize.LowPart) {
593
            Vector<char> dataBuffer(stat.cbSize.LowPart);
593
            Vector<char> dataBuffer(stat.cbSize.LowPart);
594
            ULONG read;
594
            ULONG read;
595
            // FIXME: this does a needless copy, would be better to read right into the SharedBuffer
595
            // FIXME: this does a needless copy, would be better to read right into the FragmentedSharedBuffer
596
            // or adopt the Vector or something.
596
            // or adopt the Vector or something.
597
            if (SUCCEEDED(data->Read(dataBuffer.data(), static_cast<ULONG>(dataBuffer.size()), &read)))
597
            if (SUCCEEDED(data->Read(dataBuffer.data(), static_cast<ULONG>(dataBuffer.size()), &read)))
598
                sharedBuffer->append(dataBuffer.data(), static_cast<int>(dataBuffer.size()));
598
                sharedBuffer.append(dataBuffer.data(), static_cast<int>(dataBuffer.size()));
599
        }
599
        }
600
    }
600
    }
601
601
602
    loadData(WTFMove(sharedBuffer), mimeType, textEncodingName, url, nullptr);
602
    loadData(sharedBuffer.take(), mimeType, textEncodingName, url, nullptr);
603
    return S_OK;
603
    return S_OK;
604
}
604
}
605
605
- a/Source/WebKitLegacy/win/WebFrame.h -2 / +2 lines
Lines 50-56 class HTMLFrameOwnerElement; a/Source/WebKitLegacy/win/WebFrame.h_sec1
50
class IntRect;
50
class IntRect;
51
class Page;
51
class Page;
52
class ResourceError;
52
class ResourceError;
53
class SharedBuffer;
53
class FragmentedSharedBuffer;
54
}
54
}
55
55
56
typedef const struct OpaqueJSContext* JSContextRef;
56
typedef const struct OpaqueJSContext* JSContextRef;
Lines 195-201 private: a/Source/WebKitLegacy/win/WebFrame.h_sec2
195
    ~WebFrame();
195
    ~WebFrame();
196
196
197
    void loadHTMLString(_In_ BSTR string, _In_ BSTR baseURL, _In_ BSTR unreachableURL);
197
    void loadHTMLString(_In_ BSTR string, _In_ BSTR baseURL, _In_ BSTR unreachableURL);
198
    void loadData(Ref<WebCore::SharedBuffer>&&, BSTR mimeType, BSTR textEncodingName, BSTR baseURL, BSTR failingURL);
198
    void loadData(Ref<WebCore::FragmentedSharedBuffer>&&, BSTR mimeType, BSTR textEncodingName, BSTR baseURL, BSTR failingURL);
199
    const Vector<WebCore::IntRect>& computePageRects(HDC printDC);
199
    const Vector<WebCore::IntRect>& computePageRects(HDC printDC);
200
    void setPrinting(bool printing, const WebCore::FloatSize& pageSize, const WebCore::FloatSize& originalPageSize, float maximumShrinkRatio, WebCore::AdjustViewSizeOrNot);
200
    void setPrinting(bool printing, const WebCore::FloatSize& pageSize, const WebCore::FloatSize& originalPageSize, float maximumShrinkRatio, WebCore::AdjustViewSizeOrNot);
201
    void headerAndFooterHeights(float*, float*);
201
    void headerAndFooterHeights(float*, float*);
- a/Source/WebKitLegacy/win/WebKitDLL.cpp -2 / +2 lines
Lines 165-172 void shutDownWebKit() a/Source/WebKitLegacy/win/WebKitDLL.cpp_sec1
165
}
165
}
166
166
167
//FIXME: We should consider moving this to a new file for cross-project functionality
167
//FIXME: We should consider moving this to a new file for cross-project functionality
168
WEBKIT_API RefPtr<WebCore::SharedBuffer> loadResourceIntoBuffer(const char* name);
168
WEBKIT_API RefPtr<WebCore::FragmentedSharedBuffer> loadResourceIntoBuffer(const char* name);
169
RefPtr<WebCore::SharedBuffer> loadResourceIntoBuffer(const char* name)
169
RefPtr<WebCore::FragmentedSharedBuffer> loadResourceIntoBuffer(const char* name)
170
{
170
{
171
    int idr;
171
    int idr;
172
    // temporary hack to get resource id
172
    // temporary hack to get resource id
- a/Tools/ChangeLog +49 lines
Lines 1-3 a/Tools/ChangeLog_sec1
1
2021-12-03  Jean-Yves Avenard  <jya@apple.com>
2
3
        Rename SharedBuffer classes.
4
        https://bugs.webkit.org/show_bug.cgi?id=233677
5
        rdar://problem/85963900
6
7
        Reviewed by NOBODY (OOPS!).
8
9
        SharedBuffer are renamed FragmentedSharedBuffer and
10
        ContiguousSharedBuffer to SharedBuffer to better reflect their actual
11
        types.
12
13
        * TestWebKitAPI/Tests/WTF/FileSystem.cpp:
14
        * TestWebKitAPI/Tests/WebCore/DisplayListTests.cpp:
15
        * TestWebKitAPI/Tests/WebCore/SharedBuffer.cpp:
16
        * TestWebKitAPI/Tests/WebCore/SharedBufferTest.cpp:
17
        * TestWebKitAPI/Tests/WebCore/SharedBufferTest.h:
18
        * TestWebKitAPI/Tests/WebCore/cg/DisplayListTestsCG.cpp:
19
        * TestWebKitAPI/Tests/WebCore/cocoa/SharedBuffer.mm:
20
        * TestWebKitAPI/win/TestWebCoreStubs.cpp:
21
22
2021-11-28  Jean-Yves Avenard  <jya@apple.com>
23
24
        Add SharedBufferBuilder class
25
        https://bugs.webkit.org/show_bug.cgi?id=233442
26
        rdar://85693939
27
28
        Reviewed by NOBODY (OOPS!).
29
30
        Update API tests.
31
32
        * TestWebKitAPI/Tests/WebCore/SharedBuffer.cpp:
33
        (TestWebKitAPI::TEST_F):
34
        * TestWebKitAPI/Tests/WebCore/cocoa/SharedBuffer.mm:
35
        (TestWebKitAPI::TEST_F):
36
37
2021-11-25  Jean-Yves Avenard  <jya@apple.com>
38
39
        Distinguish contiguous SharedBuffer from non-contiguous one and guarantee immutability
40
        https://bugs.webkit.org/show_bug.cgi?id=233030
41
        rdar://85333814
42
43
        Reviewed by Darin Adler.
44
45
        * TestWebKitAPI/Tests/WebCore/SharedBuffer.cpp:
46
        (TestWebKitAPI::TEST_F):
47
        * TestWebKitAPI/Tests/WebCore/cocoa/SharedBuffer.mm:
48
        (TestWebKitAPI::TEST_F):
49
1
2021-12-05  Said Abou-Hallawa  <said@apple.com>
50
2021-12-05  Said Abou-Hallawa  <said@apple.com>
2
51
3
        [GPU Process] Add the encoding/decoding for Filter and FilterEffect
52
        [GPU Process] Add the encoding/decoding for Filter and FilterEffect
- a/Tools/TestWebKitAPI/Tests/WTF/FileSystem.cpp -1 / +1 lines
Lines 44-50 static void createTestFile(const String& path) a/Tools/TestWebKitAPI/Tests/WTF/FileSystem.cpp_sec1
44
    FileSystem::closeFile(fileHandle);
44
    FileSystem::closeFile(fileHandle);
45
};
45
};
46
46
47
// FIXME: Refactor FileSystemTest and SharedBufferTest as a single class.
47
// FIXME: Refactor FileSystemTest and FragmentedSharedBufferTest as a single class.
48
class FileSystemTest : public testing::Test {
48
class FileSystemTest : public testing::Test {
49
public:
49
public:
50
    void SetUp() override
50
    void SetUp() override
- a/Tools/TestWebKitAPI/Tests/WebCore/DisplayListTests.cpp -1 / +1 lines
Lines 199-205 TEST(DisplayListTests, ItemBufferClient) a/Tools/TestWebKitAPI/Tests/WebCore/DisplayListTests.cpp_sec1
199
            return { globalBufferIdentifier, globalItemBuffer, globalItemBufferCapacity };
199
            return { globalBufferIdentifier, globalItemBuffer, globalItemBufferCapacity };
200
        }
200
        }
201
201
202
        RefPtr<SharedBuffer> encodeItemOutOfLine(const DisplayListItem& displayListItem) const final
202
        RefPtr<FragmentedSharedBuffer> encodeItemOutOfLine(const DisplayListItem& displayListItem) const final
203
        {
203
        {
204
            auto index = m_items.size();
204
            auto index = m_items.size();
205
            m_items.append(std::get<StrokePath>(displayListItem));
205
            m_items.append(std::get<StrokePath>(displayListItem));
- a/Tools/TestWebKitAPI/Tests/WebCore/SharedBuffer.cpp -109 / +156 lines
Lines 1-5 a/Tools/TestWebKitAPI/Tests/WebCore/SharedBuffer.cpp_sec1
1
/*
1
/*
2
 * Copyright (C) 2016-2017 Apple Inc. All rights reserved.
2
 * Copyright (C) 2016-2021 Apple Inc. All rights reserved.
3
 * Copyright (C) 2015 Canon Inc. All rights reserved.
3
 * Copyright (C) 2015 Canon Inc. All rights reserved.
4
 * Copyright (C) 2013 Google Inc. All rights reserved.
4
 * Copyright (C) 2013 Google Inc. All rights reserved.
5
 *
5
 *
Lines 41-120 using namespace WebCore; a/Tools/TestWebKitAPI/Tests/WebCore/SharedBuffer.cpp_sec2
41
41
42
namespace TestWebKitAPI {
42
namespace TestWebKitAPI {
43
43
44
TEST_F(SharedBufferTest, createWithContentsOfMissingFile)
44
TEST_F(FragmentedSharedBufferTest, createWithContentsOfMissingFile)
45
{
45
{
46
    RefPtr<SharedBuffer> buffer = SharedBuffer::createWithContentsOfFile(String("not_existing_file"));
46
    auto buffer = SharedBuffer::createWithContentsOfFile(String("not_existing_file"));
47
    ASSERT_NULL(buffer);
47
    ASSERT_NULL(buffer);
48
}
48
}
49
49
50
TEST_F(SharedBufferTest, createWithContentsOfExistingFile)
50
TEST_F(FragmentedSharedBufferTest, createWithContentsOfExistingFile)
51
{
51
{
52
    RefPtr<SharedBuffer> buffer = SharedBuffer::createWithContentsOfFile(tempFilePath());
52
    auto buffer = SharedBuffer::createWithContentsOfFile(tempFilePath());
53
    ASSERT_NOT_NULL(buffer);
53
    ASSERT_NOT_NULL(buffer);
54
    EXPECT_TRUE(buffer->size() == strlen(SharedBufferTest::testData()));
54
    EXPECT_TRUE(buffer->size() == strlen(FragmentedSharedBufferTest::testData()));
55
    EXPECT_TRUE(String(SharedBufferTest::testData()) == String(buffer->data(), buffer->size()));
55
    EXPECT_TRUE(String(FragmentedSharedBufferTest::testData()) == String(buffer->makeContiguous()->data(), buffer->size()));
56
}
56
}
57
57
58
TEST_F(SharedBufferTest, createWithContentsOfExistingEmptyFile)
58
TEST_F(FragmentedSharedBufferTest, createWithContentsOfExistingEmptyFile)
59
{
59
{
60
    RefPtr<SharedBuffer> buffer = SharedBuffer::createWithContentsOfFile(tempEmptyFilePath());
60
    auto buffer = SharedBuffer::createWithContentsOfFile(tempEmptyFilePath());
61
    ASSERT_NOT_NULL(buffer);
61
    ASSERT_NOT_NULL(buffer);
62
    EXPECT_TRUE(buffer->isContiguous());
62
    EXPECT_TRUE(buffer->isEmpty());
63
    EXPECT_TRUE(buffer->isEmpty());
63
}
64
}
64
65
65
TEST_F(SharedBufferTest, copyBufferCreatedWithContentsOfExistingFile)
66
TEST_F(FragmentedSharedBufferTest, copyBufferCreatedWithContentsOfExistingFile)
66
{
67
{
67
    RefPtr<SharedBuffer> buffer = SharedBuffer::createWithContentsOfFile(tempFilePath());
68
    auto buffer = SharedBuffer::createWithContentsOfFile(tempFilePath());
68
    ASSERT_NOT_NULL(buffer);
69
    ASSERT_NOT_NULL(buffer);
69
    RefPtr<SharedBuffer> copy = buffer->copy();
70
    EXPECT_TRUE(buffer->isContiguous());
71
    auto copy = buffer->copy();
70
    EXPECT_GT(buffer->size(), 0U);
72
    EXPECT_GT(buffer->size(), 0U);
71
    EXPECT_TRUE(buffer->size() == copy->size());
73
    EXPECT_TRUE(buffer->size() == copy->size());
72
    EXPECT_TRUE(!memcmp(buffer->data(), copy->data(), buffer->size()));
74
    EXPECT_TRUE(!memcmp(buffer->data(), copy->makeContiguous()->data(), buffer->size()));
73
}
75
}
74
76
75
TEST_F(SharedBufferTest, clearBufferCreatedWithContentsOfExistingFile)
77
TEST_F(FragmentedSharedBufferTest, appendBufferCreatedWithContentsOfExistingFile)
76
{
78
{
77
    RefPtr<SharedBuffer> buffer = SharedBuffer::createWithContentsOfFile(tempFilePath());
79
    RefPtr<FragmentedSharedBuffer> buffer = SharedBuffer::createWithContentsOfFile(tempFilePath());
78
    ASSERT_NOT_NULL(buffer);
80
    ASSERT_NOT_NULL(buffer);
79
    buffer->clear();
81
    SharedBufferBuilder builder;
80
    EXPECT_TRUE(!buffer->size());
82
    builder.append(*buffer);
81
    EXPECT_TRUE(!buffer->data());
83
    builder.append("a", 1);
84
    EXPECT_TRUE(builder.size() == (strlen(FragmentedSharedBufferTest::testData()) + 1));
85
    EXPECT_TRUE(!memcmp(builder.get()->makeContiguous()->data(), FragmentedSharedBufferTest::testData(), strlen(FragmentedSharedBufferTest::testData())));
86
    EXPECT_EQ('a', builder.get()->makeContiguous()->data()[strlen(FragmentedSharedBufferTest::testData())]);
82
}
87
}
83
88
84
TEST_F(SharedBufferTest, appendBufferCreatedWithContentsOfExistingFile)
89
TEST_F(FragmentedSharedBufferTest, tryCreateArrayBuffer)
85
{
86
    RefPtr<SharedBuffer> buffer = SharedBuffer::createWithContentsOfFile(tempFilePath());
87
    ASSERT_NOT_NULL(buffer);
88
    buffer->append("a", 1);
89
    EXPECT_TRUE(buffer->size() == (strlen(SharedBufferTest::testData()) + 1));
90
    EXPECT_TRUE(!memcmp(buffer->data(), SharedBufferTest::testData(), strlen(SharedBufferTest::testData())));
91
    EXPECT_EQ('a', buffer->data()[strlen(SharedBufferTest::testData())]);
92
}
93
94
TEST_F(SharedBufferTest, tryCreateArrayBuffer)
95
{
90
{
96
    char testData0[] = "Hello";
91
    char testData0[] = "Hello";
97
    char testData1[] = "World";
92
    char testData1[] = "World";
98
    char testData2[] = "Goodbye";
93
    char testData2[] = "Goodbye";
99
    RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(testData0, strlen(testData0));
94
    SharedBufferBuilder builder(testData0, strlen(testData0));
100
    sharedBuffer->append(testData1, strlen(testData1));
95
    builder.append(testData1, strlen(testData1));
101
    sharedBuffer->append(testData2, strlen(testData2));
96
    builder.append(testData2, strlen(testData2));
102
    RefPtr<ArrayBuffer> arrayBuffer = sharedBuffer->tryCreateArrayBuffer();
97
    RefPtr<ArrayBuffer> arrayBuffer = builder.get()->tryCreateArrayBuffer();
103
    char expectedConcatenation[] = "HelloWorldGoodbye";
98
    char expectedConcatenation[] = "HelloWorldGoodbye";
104
    ASSERT_EQ(strlen(expectedConcatenation), arrayBuffer->byteLength());
99
    ASSERT_EQ(strlen(expectedConcatenation), arrayBuffer->byteLength());
105
    EXPECT_EQ(0, memcmp(expectedConcatenation, arrayBuffer->data(), strlen(expectedConcatenation)));
100
    EXPECT_EQ(0, memcmp(expectedConcatenation, arrayBuffer->data(), strlen(expectedConcatenation)));
106
}
101
}
107
102
108
TEST_F(SharedBufferTest, tryCreateArrayBufferLargeSegments)
103
TEST_F(FragmentedSharedBufferTest, tryCreateArrayBufferLargeSegments)
109
{
104
{
110
    Vector<uint8_t> vector0(0x4000, 'a');
105
    Vector<uint8_t> vector0(0x4000, 'a');
111
    Vector<uint8_t> vector1(0x4000, 'b');
106
    Vector<uint8_t> vector1(0x4000, 'b');
112
    Vector<uint8_t> vector2(0x4000, 'c');
107
    Vector<uint8_t> vector2(0x4000, 'c');
113
108
114
    RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(WTFMove(vector0));
109
    SharedBufferBuilder builder(WTFMove(vector0));
115
    sharedBuffer->append(WTFMove(vector1));
110
    builder.append(WTFMove(vector1));
116
    sharedBuffer->append(WTFMove(vector2));
111
    builder.append(WTFMove(vector2));
117
    RefPtr<ArrayBuffer> arrayBuffer = sharedBuffer->tryCreateArrayBuffer();
112
    RefPtr<ArrayBuffer> arrayBuffer = builder.get()->tryCreateArrayBuffer();
118
    ASSERT_EQ(0x4000U + 0x4000U + 0x4000U, arrayBuffer->byteLength());
113
    ASSERT_EQ(0x4000U + 0x4000U + 0x4000U, arrayBuffer->byteLength());
119
    int position = 0;
114
    int position = 0;
120
    for (int i = 0; i < 0x4000; ++i) {
115
    for (int i = 0; i < 0x4000; ++i) {
Lines 131-137 TEST_F(SharedBufferTest, tryCreateArrayBufferLargeSegments) a/Tools/TestWebKitAPI/Tests/WebCore/SharedBuffer.cpp_sec3
131
    }
126
    }
132
}
127
}
133
128
134
TEST_F(SharedBufferTest, copy)
129
TEST_F(FragmentedSharedBufferTest, copy)
135
{
130
{
136
    char testData[] = "Habitasse integer eros tincidunt a scelerisque! Enim elit? Scelerisque magnis,"
131
    char testData[] = "Habitasse integer eros tincidunt a scelerisque! Enim elit? Scelerisque magnis,"
137
    "et montes ultrices tristique a! Pid. Velit turpis, dapibus integer rhoncus sociis amet facilisis,"
132
    "et montes ultrices tristique a! Pid. Velit turpis, dapibus integer rhoncus sociis amet facilisis,"
Lines 151-167 TEST_F(SharedBufferTest, copy) a/Tools/TestWebKitAPI/Tests/WebCore/SharedBuffer.cpp_sec4
151
    "mattis dignissim massa ac pulvinar urna, nunc ut. Sagittis, aliquet penatibus proin lorem, pulvinar lectus,"
146
    "mattis dignissim massa ac pulvinar urna, nunc ut. Sagittis, aliquet penatibus proin lorem, pulvinar lectus,"
152
    "augue proin! Ac, arcu quis. Placerat habitasse, ridiculus ridiculus.";
147
    "augue proin! Ac, arcu quis. Placerat habitasse, ridiculus ridiculus.";
153
    unsigned length = strlen(testData);
148
    unsigned length = strlen(testData);
154
    RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(testData, length);
149
    SharedBufferBuilder builder1(testData, length);
155
    sharedBuffer->append(testData, length);
150
    builder1.append(testData, length);
156
    sharedBuffer->append(testData, length);
151
    builder1.append(testData, length);
157
    sharedBuffer->append(testData, length);
152
    builder1.append(testData, length);
158
    // sharedBuffer must contain data more than segmentSize (= 0x1000) to check copy().
153
    // sharedBuffer must contain data more than segmentSize (= 0x1000) to check copy().
159
    ASSERT_EQ(length * 4, sharedBuffer->size());
154
    EXPECT_EQ(length * 4, builder1.size());
160
    RefPtr<SharedBuffer> clone = sharedBuffer->copy();
155
    RefPtr<FragmentedSharedBuffer> clone = builder1.copy();
161
    ASSERT_EQ(length * 4, clone->size());
156
    EXPECT_EQ(length * 4, clone->size());
162
    ASSERT_EQ(0, memcmp(clone->data(), sharedBuffer->data(), clone->size()));
157
    EXPECT_EQ(0, memcmp(clone->makeContiguous()->data(), builder1.get()->makeContiguous()->data(), clone->size()));
163
    clone->append(testData, length);
158
164
    ASSERT_EQ(length * 5, clone->size());
159
    SharedBufferBuilder builder2;
160
    builder2.append(*clone);
161
    builder2.append(testData, length);
162
    EXPECT_EQ(length * 5, builder2.size());
163
    auto buffer = builder2.take();
164
    EXPECT_EQ(length * 5, buffer->size());
165
    // builder is now empty.
166
    EXPECT_EQ(0U, builder2.size());
167
    EXPECT_TRUE(builder2.isNull());
168
    EXPECT_TRUE(builder2.isEmpty());
169
}
170
171
TEST_F(FragmentedSharedBufferTest, builder)
172
{
173
    char testData0[] = "Hello";
174
    SharedBufferBuilder builder1(testData0, strlen(testData0));
175
    EXPECT_FALSE(builder1.isNull());
176
    EXPECT_FALSE(builder1.isEmpty());
177
    auto copy = builder1.copy();
178
    auto buffer = builder1.take();
179
    EXPECT_TRUE(builder1.isNull());
180
    EXPECT_TRUE(builder1.isEmpty());
181
    EXPECT_NE(copy.ptr(), buffer.ptr()); // We have different FragmentedSharedBuffer
182
    EXPECT_EQ(copy.get(), buffer.get()); // But their content is identical
183
184
    SharedBufferBuilder builder2;
185
    EXPECT_TRUE(builder2.isNull());
186
    EXPECT_TRUE(builder2.isEmpty());
187
    builder2.append(testData0, strlen(testData0));
188
    EXPECT_FALSE(builder2.isNull());
189
    EXPECT_FALSE(builder2.isEmpty());
190
    builder2.reset();
191
    EXPECT_TRUE(builder2.isNull());
192
    EXPECT_TRUE(builder2.isEmpty());
193
    builder2.empty();
194
    EXPECT_FALSE(builder2.isNull());
195
    EXPECT_TRUE(builder2.isEmpty());
165
}
196
}
166
197
167
static void checkBuffer(const uint8_t* buffer, size_t bufferLength, const char* expected)
198
static void checkBuffer(const uint8_t* buffer, size_t bufferLength, const char* expected)
Lines 173-242 static void checkBuffer(const uint8_t* buffer, size_t bufferLength, const char* a/Tools/TestWebKitAPI/Tests/WebCore/SharedBuffer.cpp_sec5
173
        EXPECT_EQ(buffer[i], expected[i]);
204
        EXPECT_EQ(buffer[i], expected[i]);
174
}
205
}
175
206
176
TEST_F(SharedBufferTest, getSomeData)
207
TEST_F(FragmentedSharedBufferTest, getSomeData)
177
{
208
{
178
    Vector<uint8_t> s1 = {'a', 'b', 'c', 'd'};
209
    Vector<uint8_t> s1 = { 'a', 'b', 'c', 'd' };
179
    Vector<uint8_t> s2 = {'e', 'f', 'g', 'h'};
210
    Vector<uint8_t> s2 = { 'e', 'f', 'g', 'h' };
180
    Vector<uint8_t> s3 = {'i', 'j', 'k', 'l'};
211
    Vector<uint8_t> s3 = { 'i', 'j', 'k', 'l' };
181
    
212
182
    auto buffer = SharedBuffer::create();
213
    SharedBufferBuilder builder;
183
    buffer->append(WTFMove(s1));
214
    builder.append(WTFMove(s1));
184
    buffer->append(WTFMove(s2));
215
    builder.append(WTFMove(s2));
185
    buffer->append(WTFMove(s3));
216
    builder.append(WTFMove(s3));
217
    auto buffer = builder.take();
186
    
218
    
187
    auto abcd = buffer->getSomeData(0);
219
    auto abcd = buffer->getSomeData(0);
188
    auto gh = buffer->getSomeData(6);
220
    auto gh1 = buffer->getSomeData(6);
189
    auto h = buffer->getSomeData(7);
221
    auto h = buffer->getSomeData(7);
190
    auto ijkl = buffer->getSomeData(8);
222
    auto ijkl = buffer->getSomeData(8);
191
    auto kl = buffer->getSomeData(10);
223
    auto kl = buffer->getSomeData(10);
192
    auto abcdefghijkl = buffer->data();
224
    auto contiguousBuffer = buffer->makeContiguous();
193
    auto ghijkl = buffer->getSomeData(6);
225
    auto abcdefghijkl = contiguousBuffer->data();
226
    auto gh2 = buffer->getSomeData(6);
227
    auto ghijkl = contiguousBuffer->getSomeData(6);
194
    auto l = buffer->getSomeData(11);
228
    auto l = buffer->getSomeData(11);
195
    checkBuffer(abcd.data(), abcd.size(), "abcd");
229
    checkBuffer(abcd.data(), abcd.size(), "abcd");
196
    checkBuffer(gh.data(), gh.size(), "gh");
230
    checkBuffer(gh1.data(), gh1.size(), "gh");
197
    checkBuffer(h.data(), h.size(), "h");
231
    checkBuffer(h.data(), h.size(), "h");
198
    checkBuffer(ijkl.data(), ijkl.size(), "ijkl");
232
    checkBuffer(ijkl.data(), ijkl.size(), "ijkl");
199
    checkBuffer(kl.data(), kl.size(), "kl");
233
    checkBuffer(kl.data(), kl.size(), "kl");
200
    checkBuffer(abcdefghijkl, buffer->size(), "abcdefghijkl");
234
    checkBuffer(abcdefghijkl, buffer->size(), "abcdefghijkl");
235
    checkBuffer(gh2.data(), gh2.size(), "gh");
201
    checkBuffer(ghijkl.data(), ghijkl.size(), "ghijkl");
236
    checkBuffer(ghijkl.data(), ghijkl.size(), "ghijkl");
237
    EXPECT_EQ(gh1.size(), gh2.size());
238
    checkBuffer(gh1.data(), gh1.size(), gh2.dataAsCharPtr());
202
    checkBuffer(l.data(), l.size(), "l");
239
    checkBuffer(l.data(), l.size(), "l");
203
}
240
}
204
241
205
TEST_F(SharedBufferTest, isEqualTo)
242
TEST_F(FragmentedSharedBufferTest, isEqualTo)
206
{
243
{
207
    auto makeBuffer = [] (Vector<Vector<uint8_t>>&& contents) {
244
    auto makeBuffer = [] (Vector<Vector<uint8_t>>&& contents) {
208
        auto buffer = SharedBuffer::create();
245
        SharedBufferBuilder builder;
209
        for (auto& content : contents)
246
        for (auto& content : contents)
210
            buffer->append(WTFMove(content));
247
            builder.append(WTFMove(content));
211
        return buffer;
248
        return builder.take();
212
    };
249
    };
213
    auto buffer1 = makeBuffer({{'a', 'b', 'c', 'd'}});
250
    auto buffer1 = makeBuffer({ { 'a', 'b', 'c', 'd' } });
214
    EXPECT_EQ(buffer1.get(), buffer1.get());
251
    EXPECT_EQ(buffer1.get(), buffer1.get());
215
252
216
    buffer1->append(Vector<uint8_t>({'a', 'b', 'c', 'd'}));
253
    SharedBufferBuilder builder(WTFMove(buffer1));
217
    EXPECT_EQ(buffer1.get(), makeBuffer({{'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'}}).get());
254
    builder.append(Vector<uint8_t>({ 'a', 'b', 'c', 'd' }));
218
    EXPECT_EQ(makeBuffer({{'a'}, {'b', 'c'}, {'d'}}).get(), makeBuffer({{'a', 'b'}, {'c', 'd'}}).get());
255
    EXPECT_EQ(*builder.get(), makeBuffer({ { 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd' } }).get());
219
    EXPECT_NE(makeBuffer({{'a', 'b'}}).get(), makeBuffer({{'a', 'b', 'c'}}).get());
256
220
    EXPECT_NE(makeBuffer({{'a', 'b'}}).get(), makeBuffer({{'b', 'c'}}).get());
257
    EXPECT_EQ(makeBuffer({ { 'a' }, { 'b', 'c' }, { 'd' } }).get(), makeBuffer({ { 'a', 'b' }, { 'c', 'd' } }).get());
221
    EXPECT_NE(makeBuffer({{'a'}, {'b'}}).get(), makeBuffer({{'a'}, {'a'}}).get());
258
    EXPECT_NE(makeBuffer({ { 'a', 'b' } }).get(), makeBuffer({ { 'a', 'b', 'c' } }).get());
259
    EXPECT_NE(makeBuffer({ { 'a', 'b' } }).get(), makeBuffer({ { 'b', 'c' } }).get());
260
    EXPECT_NE(makeBuffer({ { 'a' }, { 'b' } }).get(), makeBuffer({ { 'a' }, { 'a' } }).get());
222
}
261
}
223
262
224
TEST_F(SharedBufferTest, toHexString)
263
TEST_F(FragmentedSharedBufferTest, toHexString)
225
{
264
{
226
    Vector<uint8_t> t1 = {0x11, 0x5, 0x12};
265
    Vector<uint8_t> t1 = {0x11, 0x5, 0x12};
227
    auto buffer = SharedBuffer::create();
266
    SharedBufferBuilder builder;
228
    buffer->append(WTFMove(t1));
267
    builder.append(WTFMove(t1));
268
    auto buffer = builder.take();
229
    String result = buffer->toHexString();
269
    String result = buffer->toHexString();
230
    EXPECT_EQ(result, "110512");
270
    EXPECT_EQ(result, "110512");
231
    buffer->clear();
271
    builder.reset();
272
    buffer = builder.take();
232
    EXPECT_EQ(buffer->toHexString(), "");
273
    EXPECT_EQ(buffer->toHexString(), "");
233
}
274
}
234
275
235
TEST_F(SharedBufferTest, read)
276
TEST_F(FragmentedSharedBufferTest, read)
236
{
277
{
237
    const char* const simpleText = "This is a simple test.";
278
    const char* const simpleText = "This is a simple test.";
238
279
239
    auto check = [](SharedBuffer& sharedBuffer) {
280
    auto check = [](FragmentedSharedBuffer& sharedBuffer) {
240
        Vector<uint8_t> data = sharedBuffer.read(4, 3);
281
        Vector<uint8_t> data = sharedBuffer.read(4, 3);
241
        EXPECT_EQ(data.size(), 3u);
282
        EXPECT_EQ(data.size(), 3u);
242
        EXPECT_EQ(String(data.data(), 3), " is");
283
        EXPECT_EQ(String(data.data(), 3), " is");
Lines 249-264 TEST_F(SharedBufferTest, read) a/Tools/TestWebKitAPI/Tests/WebCore/SharedBuffer.cpp_sec6
249
    auto sharedBuffer = SharedBuffer::create(simpleText, strlen(simpleText));
290
    auto sharedBuffer = SharedBuffer::create(simpleText, strlen(simpleText));
250
    check(sharedBuffer);
291
    check(sharedBuffer);
251
292
252
    sharedBuffer = SharedBuffer::create();
293
    SharedBufferBuilder builder;
253
    for (size_t i = 0; i < strlen(simpleText); i++)
294
    for (size_t i = 0; i < strlen(simpleText); i++)
254
        sharedBuffer->append(&simpleText[i], 1);
295
        builder.append(&simpleText[i], 1);
255
    check(sharedBuffer);
296
    check(builder.take());
297
    EXPECT_TRUE(builder.isNull() && !builder);
298
    EXPECT_EQ(builder.size(), 0u);
256
299
257
    sharedBuffer = SharedBuffer::create();
258
    for (size_t i = 0; i < strlen(simpleText); i += 2)
300
    for (size_t i = 0; i < strlen(simpleText); i += 2)
259
        sharedBuffer->append(&simpleText[i], 2);
301
        builder.append(&simpleText[i], 2);
260
    EXPECT_EQ(sharedBuffer->size(), strlen(simpleText));
302
    EXPECT_EQ(builder.size(), strlen(simpleText));
261
    check(sharedBuffer);
303
    check(builder.take());
262
}
304
}
263
305
264
#if ENABLE(MHTML)
306
#if ENABLE(MHTML)
Lines 266-272 TEST_F(SharedBufferTest, read) a/Tools/TestWebKitAPI/Tests/WebCore/SharedBuffer.cpp_sec7
266
template< typename T, size_t N >
308
template< typename T, size_t N >
267
constexpr size_t arraysize( const T (&)[N] ) { return N; }
309
constexpr size_t arraysize( const T (&)[N] ) { return N; }
268
310
269
static void readAllChunks(std::vector<String>* chunks, SharedBuffer& buffer, const String& separator = "\r\n", bool includeSeparator = false)
311
static void readAllChunks(std::vector<String>* chunks, FragmentedSharedBuffer& buffer, const String& separator = "\r\n", bool includeSeparator = false)
270
{
312
{
271
    SharedBufferChunkReader chunkReader(&buffer, separator.utf8().data());
313
    SharedBufferChunkReader chunkReader(&buffer, separator.utf8().data());
272
    String chunk = chunkReader.nextChunkAsUTF8StringWithLatin1Fallback(includeSeparator);
314
    String chunk = chunkReader.nextChunkAsUTF8StringWithLatin1Fallback(includeSeparator);
Lines 299-305 static void checkDataInRange(const Vector<uint8_t>& data, size_t start, size_t l a/Tools/TestWebKitAPI/Tests/WebCore/SharedBuffer.cpp_sec8
299
341
300
TEST_F(SharedBufferChunkReaderTest, includeSeparator)
342
TEST_F(SharedBufferChunkReaderTest, includeSeparator)
301
{
343
{
302
    auto check = [](SharedBuffer& sharedBuffer) {
344
    auto check = [](FragmentedSharedBuffer& sharedBuffer) {
303
        SharedBufferChunkReader chunkReader(&sharedBuffer, "\x10\x11\x12");
345
        SharedBufferChunkReader chunkReader(&sharedBuffer, "\x10\x11\x12");
304
        Vector<uint8_t> out;
346
        Vector<uint8_t> out;
305
        EXPECT_TRUE(chunkReader.nextChunk(out));
347
        EXPECT_TRUE(chunkReader.nextChunk(out));
Lines 313-334 TEST_F(SharedBufferChunkReaderTest, includeSeparator) a/Tools/TestWebKitAPI/Tests/WebCore/SharedBuffer.cpp_sec9
313
    uint8_t data[256];
355
    uint8_t data[256];
314
    for (size_t i = 0; i < 256; ++i)
356
    for (size_t i = 0; i < 256; ++i)
315
        data[i] = i;
357
        data[i] = i;
316
317
    auto sharedBuffer = SharedBuffer::create(data, 256);
358
    auto sharedBuffer = SharedBuffer::create(data, 256);
318
    check(sharedBuffer);
359
    check(sharedBuffer);
319
    sharedBuffer = SharedBuffer::create();
360
361
    SharedBufferBuilder builder(data, 256);
362
    check(builder.take());
363
320
    for (size_t i = 0; i < 256; ++i) {
364
    for (size_t i = 0; i < 256; ++i) {
321
        char c = i;
365
        char c = i;
322
        sharedBuffer->append(&c, 1);
366
        builder.append(&c, 1);
323
    }
367
    }
324
    check(sharedBuffer);
368
    check(builder.take());
325
}
369
}
326
370
327
TEST_F(SharedBufferChunkReaderTest, peekData)
371
TEST_F(SharedBufferChunkReaderTest, peekData)
328
{
372
{
329
    const char* const simpleText = "This is a simple test.";
373
    const char* const simpleText = "This is a simple test.";
330
374
331
    auto check = [](SharedBuffer& sharedBuffer) {
375
    auto check = [](FragmentedSharedBuffer& sharedBuffer) {
332
        SharedBufferChunkReader chunkReader(&sharedBuffer, "is");
376
        SharedBufferChunkReader chunkReader(&sharedBuffer, "is");
333
377
334
        String chunk = chunkReader.nextChunkAsUTF8StringWithLatin1Fallback();
378
        String chunk = chunkReader.nextChunkAsUTF8StringWithLatin1Fallback();
Lines 358-379 TEST_F(SharedBufferChunkReaderTest, peekData) a/Tools/TestWebKitAPI/Tests/WebCore/SharedBuffer.cpp_sec10
358
    auto sharedBuffer = SharedBuffer::create(simpleText, strlen(simpleText));
402
    auto sharedBuffer = SharedBuffer::create(simpleText, strlen(simpleText));
359
    check(sharedBuffer);
403
    check(sharedBuffer);
360
404
361
    sharedBuffer = SharedBuffer::create();
405
    SharedBufferBuilder builder(simpleText, strlen(simpleText));
406
    check(builder.take());
407
362
    for (size_t i = 0; i < strlen(simpleText); i++)
408
    for (size_t i = 0; i < strlen(simpleText); i++)
363
        sharedBuffer->append(&simpleText[i], 1);
409
        builder.append(&simpleText[i], 1);
364
    check(sharedBuffer);
410
    check(builder.take());
365
411
366
    sharedBuffer = SharedBuffer::create();
367
    for (size_t i = 0; i < strlen(simpleText); i += 2)
412
    for (size_t i = 0; i < strlen(simpleText); i += 2)
368
        sharedBuffer->append(&simpleText[i], 2);
413
        builder.append(&simpleText[i], 2);
369
    EXPECT_EQ(sharedBuffer->size(), strlen(simpleText));
414
    EXPECT_EQ(builder.size(), strlen(simpleText));
370
    check(sharedBuffer);
415
    check(builder.take());
371
}
416
}
372
417
373
TEST_F(SharedBufferChunkReaderTest, readAllChunksInMultiSegment)
418
TEST_F(SharedBufferChunkReaderTest, readAllChunksInMultiSegment)
374
{
419
{
375
    const char* const simpleText = "This is the most ridiculous history there is.";
420
    const char* const simpleText = "This is the most ridiculous history there is.";
376
    auto check = [](SharedBuffer& sharedBuffer) {
421
    auto check = [](FragmentedSharedBuffer& sharedBuffer) {
377
        std::vector<String> chunks;
422
        std::vector<String> chunks;
378
        const char* const expectedChunks1WithoutSeparator[] = { "Th", "s ", "s the most r", "d", "culous h", "story there ", "s." };
423
        const char* const expectedChunks1WithoutSeparator[] = { "Th", "s ", "s the most r", "d", "culous h", "story there ", "s." };
379
        readAllChunks(&chunks, sharedBuffer, "i");
424
        readAllChunks(&chunks, sharedBuffer, "i");
Lines 406-422 TEST_F(SharedBufferChunkReaderTest, readAllChunksInMultiSegment) a/Tools/TestWebKitAPI/Tests/WebCore/SharedBuffer.cpp_sec11
406
    };
451
    };
407
    auto sharedBuffer = SharedBuffer::create(simpleText, strlen(simpleText));
452
    auto sharedBuffer = SharedBuffer::create(simpleText, strlen(simpleText));
408
    check(sharedBuffer);
453
    check(sharedBuffer);
409
    sharedBuffer = SharedBuffer::create();
454
455
    SharedBufferBuilder builder(simpleText, strlen(simpleText));
456
    check(builder.take());
457
410
    for (size_t i = 0; i < strlen(simpleText); i++)
458
    for (size_t i = 0; i < strlen(simpleText); i++)
411
        sharedBuffer->append(&simpleText[i], 1);
459
        builder.append(&simpleText[i], 1);
412
    EXPECT_EQ(sharedBuffer->size(), strlen(simpleText));
460
    EXPECT_EQ(builder.size(), strlen(simpleText));
413
    check(sharedBuffer);
461
    check(builder.take());
414
462
415
    sharedBuffer = SharedBuffer::create();
416
    for (size_t i = 0; i < strlen(simpleText); i += 5)
463
    for (size_t i = 0; i < strlen(simpleText); i += 5)
417
        sharedBuffer->append(&simpleText[i], 5);
464
        builder.append(&simpleText[i], 5);
418
    EXPECT_EQ(sharedBuffer->size(), strlen(simpleText));
465
    EXPECT_EQ(builder.size(), strlen(simpleText));
419
    check(sharedBuffer);
466
    check(builder.take());
420
}
467
}
421
468
422
TEST_F(SharedBufferChunkReaderTest, changingIterator)
469
TEST_F(SharedBufferChunkReaderTest, changingIterator)
- a/Tools/TestWebKitAPI/Tests/WebCore/SharedBufferTest.cpp -2 / +2 lines
Lines 31-37 a/Tools/TestWebKitAPI/Tests/WebCore/SharedBufferTest.cpp_sec1
31
31
32
namespace TestWebKitAPI {
32
namespace TestWebKitAPI {
33
33
34
void SharedBufferTest::SetUp()
34
void FragmentedSharedBufferTest::SetUp()
35
{
35
{
36
    WTF::initializeMainThread();
36
    WTF::initializeMainThread();
37
37
Lines 45-51 void SharedBufferTest::SetUp() a/Tools/TestWebKitAPI/Tests/WebCore/SharedBufferTest.cpp_sec2
45
    FileSystem::closeFile(handle);
45
    FileSystem::closeFile(handle);
46
}
46
}
47
47
48
void SharedBufferTest::TearDown()
48
void FragmentedSharedBufferTest::TearDown()
49
{
49
{
50
    FileSystem::deleteFile(m_tempFilePath);
50
    FileSystem::deleteFile(m_tempFilePath);
51
    FileSystem::deleteFile(m_tempEmptyFilePath);
51
    FileSystem::deleteFile(m_tempEmptyFilePath);
- a/Tools/TestWebKitAPI/Tests/WebCore/SharedBufferTest.h -1 / +1 lines
Lines 29-35 a/Tools/TestWebKitAPI/Tests/WebCore/SharedBufferTest.h_sec1
29
29
30
namespace TestWebKitAPI {
30
namespace TestWebKitAPI {
31
31
32
class SharedBufferTest : public testing::Test {
32
class FragmentedSharedBufferTest : public testing::Test {
33
public:
33
public:
34
    void SetUp() override;
34
    void SetUp() override;
35
    void TearDown() override;
35
    void TearDown() override;
- a/Tools/TestWebKitAPI/Tests/WebCore/cg/DisplayListTestsCG.cpp -1 / +1 lines
Lines 104-110 private: a/Tools/TestWebKitAPI/Tests/WebCore/cg/DisplayListTestsCG.cpp_sec1
104
        return { globalBufferIdentifier, globalItemBuffer, globalItemBufferCapacity };
104
        return { globalBufferIdentifier, globalItemBuffer, globalItemBufferCapacity };
105
    }
105
    }
106
106
107
    RefPtr<SharedBuffer> encodeItemOutOfLine(const DisplayListItem&) const final
107
    RefPtr<FragmentedSharedBuffer> encodeItemOutOfLine(const DisplayListItem&) const final
108
    {
108
    {
109
        return SharedBuffer::create();
109
        return SharedBuffer::create();
110
    }
110
    }
- a/Tools/TestWebKitAPI/Tests/WebCore/cocoa/SharedBuffer.mm -16 / +17 lines
Lines 1-5 a/Tools/TestWebKitAPI/Tests/WebCore/cocoa/SharedBuffer.mm_sec1
1
/*
1
/*
2
 * Copyright (C) 2017-2019 Apple Inc. All rights reserved.
2
 * Copyright (C) 2017-2021 Apple Inc. All rights reserved.
3
 *
3
 *
4
 * Redistribution and use in source and binary forms, with or without
4
 * Redistribution and use in source and binary forms, with or without
5
 * modification, are permitted provided that the following conditions
5
 * modification, are permitted provided that the following conditions
Lines 45-63 static void expectDataArraysEqual(NSArray<NSData *> *expected, NSArray<NSData *> a/Tools/TestWebKitAPI/Tests/WebCore/cocoa/SharedBuffer.mm_sec2
45
    }
45
    }
46
}
46
}
47
47
48
TEST_F(SharedBufferTest, createNSDataArray)
48
TEST_F(FragmentedSharedBufferTest, createNSDataArray)
49
{
49
{
50
    @autoreleasepool {
50
    @autoreleasepool {
51
        auto buffer = SharedBuffer::create();
51
        SharedBufferBuilder builder;
52
        expectDataArraysEqual(nil, buffer->createNSDataArray().get());
52
        builder.empty();
53
        expectDataArraysEqual(nil, builder.get()->createNSDataArray().get());
53
54
54
        NSData *helloData = [NSData dataWithBytes:"hello" length:5];
55
        NSData *helloData = [NSData dataWithBytes:"hello" length:5];
55
        buffer->append((const char*)helloData.bytes, helloData.length);
56
        builder.append((const char*)helloData.bytes, helloData.length);
56
        expectDataArraysEqual(@[ helloData ], buffer->createNSDataArray().get());
57
        expectDataArraysEqual(@[ helloData ], builder.get()->createNSDataArray().get());
57
58
58
        NSData *worldData = [NSData dataWithBytes:"world" length:5];
59
        NSData *worldData = [NSData dataWithBytes:"world" length:5];
59
        buffer->append((__bridge CFDataRef)worldData);
60
        builder.append((__bridge CFDataRef)worldData);
60
        expectDataArraysEqual(@[ helloData, worldData ], buffer->createNSDataArray().get());
61
        expectDataArraysEqual(@[ helloData, worldData ], builder.get()->createNSDataArray().get());
61
62
62
        expectDataArraysEqual(@[ helloData ], SharedBuffer::create(helloData)->createNSDataArray().get());
63
        expectDataArraysEqual(@[ helloData ], SharedBuffer::create(helloData)->createNSDataArray().get());
63
        expectDataArraysEqual(@[ worldData ], SharedBuffer::create((__bridge CFDataRef)worldData)->createNSDataArray().get());
64
        expectDataArraysEqual(@[ worldData ], SharedBuffer::create((__bridge CFDataRef)worldData)->createNSDataArray().get());
Lines 66-100 TEST_F(SharedBufferTest, createNSDataArray) a/Tools/TestWebKitAPI/Tests/WebCore/cocoa/SharedBuffer.mm_sec3
66
    }
67
    }
67
}
68
}
68
69
69
TEST_F(SharedBufferTest, createNSDataForDataSegment)
70
TEST_F(FragmentedSharedBufferTest, createNSDataForDataSegment)
70
{
71
{
71
    @autoreleasepool {
72
    @autoreleasepool {
72
        auto buffer = SharedBuffer::create();
73
        SharedBufferBuilder builder;
73
74
74
        NSData *helloData = [NSData dataWithBytes:"hello" length:5];
75
        NSData *helloData = [NSData dataWithBytes:"hello" length:5];
75
        buffer->append((const char*)helloData.bytes, helloData.length);
76
        builder.append((const char*)helloData.bytes, helloData.length);
76
77
77
        NSData *worldData = [NSData dataWithBytes:"world" length:5];
78
        NSData *worldData = [NSData dataWithBytes:"world" length:5];
78
        buffer->append((__bridge CFDataRef)worldData);
79
        builder.append((__bridge CFDataRef)worldData);
79
80
80
        NSArray *expectedData = @[ helloData, worldData ];
81
        NSArray *expectedData = @[ helloData, worldData ];
81
        NSUInteger expectedSize = helloData.length + worldData.length;
82
        NSUInteger expectedSize = helloData.length + worldData.length;
82
83
83
        NSUInteger segmentCount = 0;
84
        NSUInteger segmentCount = 0;
84
        for (auto& segment : buffer.get())
85
        for (auto& segment : *builder.get())
85
            EXPECT_TRUE([segment.segment->createNSData() isEqualToData:expectedData[segmentCount++]]);
86
            EXPECT_TRUE([segment.segment->createNSData() isEqualToData:expectedData[segmentCount++]]);
86
        EXPECT_EQ(expectedData.count, segmentCount);
87
        EXPECT_EQ(expectedData.count, segmentCount);
87
88
88
        NSUInteger position = 0;
89
        NSUInteger position = 0;
89
        segmentCount = 0;
90
        segmentCount = 0;
90
        while (buffer->size() > position) {
91
        while (builder.size() > position) {
91
            auto incrementalData = buffer->getSomeData(position);
92
            auto incrementalData = builder.get()->getSomeData(position);
92
            EXPECT_TRUE([incrementalData.createNSData() isEqualToData:expectedData[segmentCount++]]);
93
            EXPECT_TRUE([incrementalData.createNSData() isEqualToData:expectedData[segmentCount++]]);
93
            position += incrementalData.size();
94
            position += incrementalData.size();
94
        }
95
        }
95
        EXPECT_EQ(expectedData.count, segmentCount);
96
        EXPECT_EQ(expectedData.count, segmentCount);
96
97
97
        auto lastByte = buffer->getSomeData(expectedSize - 1);
98
        auto lastByte = builder.get()->getSomeData(expectedSize - 1);
98
        EXPECT_TRUE([lastByte.createNSData() isEqualToData:[@"d" dataUsingEncoding:NSASCIIStringEncoding]]);
99
        EXPECT_TRUE([lastByte.createNSData() isEqualToData:[@"d" dataUsingEncoding:NSASCIIStringEncoding]]);
99
        EXPECT_EQ(1LU, lastByte.size());
100
        EXPECT_EQ(1LU, lastByte.size());
100
    }
101
    }
- a/Tools/TestWebKitAPI/win/TestWebCoreStubs.cpp -1 / +1 lines
Lines 25-31 a/Tools/TestWebKitAPI/win/TestWebCoreStubs.cpp_sec1
25
25
26
#include <WebCore/SharedBuffer.h>
26
#include <WebCore/SharedBuffer.h>
27
27
28
RefPtr<WebCore::SharedBuffer> loadResourceIntoBuffer(const char*)
28
RefPtr<WebCore::FragmentedSharedBuffer> loadResourceIntoBuffer(const char*)
29
{
29
{
30
    return nullptr;
30
    return nullptr;
31
}
31
}

Return to Bug 233923