-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathSerializedScriptValue.cpp
More file actions
6847 lines (6263 loc) · 252 KB
/
SerializedScriptValue.cpp
File metadata and controls
6847 lines (6263 loc) · 252 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2009-2023 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "config.h"
#include "SerializedScriptValue.h"
#include "BunString.h"
// #include "BlobRegistry.h"
// #include "ByteArrayPixelBuffer.h"
#include "CryptoKeyAES.h"
#include "CryptoKeyEC.h"
#include "CryptoKeyHMAC.h"
#include "CryptoKeyOKP.h"
#include "CryptoKeyRSA.h"
#include "CryptoKeyRSAComponents.h"
#include "CryptoKeyRaw.h"
// #include "IDBValue.h"
// #include "ImageBitmapBacking.h"
// #include "JSAudioWorkletGlobalScope.h"
// #include "JSBlob.h"
#include "JSCryptoKey.h"
#include "JSDOMBinding.h"
#include "JSDOMConvertBufferSource.h"
#include "JSDOMException.h"
#include "JSDOMGlobalObject.h"
// #include "JSDOMMatrix.h"
// #include "JSDOMPoint.h"
// #include "JSDOMQuad.h"
// #include "JSDOMRect.h"
// #include "JSExecState.h"
// #include "JSFile.h"
// #include "JSFileList.h"
// #include "JSIDBSerializationGlobalObject.h"
// #include "JSImageBitmap.h"
// #include "JSImageData.h"
#include "JSMessagePort.h"
// #include "JSNavigator.h"
// #include "JSRTCCertificate.h"
// #include "JSRTCDataChannel.h"
// #include "JSWebCodecsEncodedVideoChunk.h"
// #include "JSWebCodecsVideoFrame.h"
#include "ScriptExecutionContext.h"
// #include "WebCodecsEncodedVideoChunk.h"
#include "WebCoreJSClientData.h"
#include <JavaScriptCore/APICast.h>
#include <JavaScriptCore/BigIntObject.h>
#include <JavaScriptCore/BooleanObject.h>
#include <JavaScriptCore/TopExceptionScope.h>
#include <JavaScriptCore/DateInstance.h>
#include <JavaScriptCore/Error.h>
#include <JavaScriptCore/ErrorInstance.h>
#include <JavaScriptCore/Exception.h>
#include <JavaScriptCore/ExceptionHelpers.h>
#include <JavaScriptCore/IterationKind.h>
#include <JavaScriptCore/JSArrayBuffer.h>
#include <JavaScriptCore/ArrayBuffer.h>
#include <JavaScriptCore/JSArrayBufferView.h>
#include <JavaScriptCore/JSCInlines.h>
#include <JavaScriptCore/JSArrayInlines.h>
#include <JavaScriptCore/ButterflyInlines.h>
#include <JavaScriptCore/ObjectInitializationScope.h>
#include <JavaScriptCore/JSDataView.h>
#include <JavaScriptCore/JSMapInlines.h>
#include <JavaScriptCore/JSMapIterator.h>
#include <JavaScriptCore/JSSetInlines.h>
#include <JavaScriptCore/JSSetIterator.h>
#include <JavaScriptCore/JSTypedArrays.h>
#include <JavaScriptCore/JSWebAssemblyMemory.h>
#include <JavaScriptCore/JSWebAssemblyModule.h>
#include <JavaScriptCore/NumberObject.h>
#include <JavaScriptCore/ObjectConstructor.h>
#include <JavaScriptCore/PropertyNameArray.h>
#include <JavaScriptCore/RegExp.h>
#include <JavaScriptCore/RegExpObject.h>
#include <JavaScriptCore/TypedArrayInlines.h>
#include <JavaScriptCore/TypedArrays.h>
#include <JavaScriptCore/WasmModule.h>
#include <JavaScriptCore/YarrFlags.h>
#include <limits>
#include <wtf/CheckedArithmetic.h>
#include <wtf/CompletionHandler.h>
#include <wtf/MainThread.h>
#include <wtf/RunLoop.h>
#include <wtf/Vector.h>
#include <wtf/threads/BinarySemaphore.h>
#include "ZigGlobalObject.h"
#include "blob.h"
#include "ZigGeneratedClasses.h"
#include "JSX509Certificate.h"
#include "ncrypto.h"
#include "JSKeyObject.h"
#include "JSSecretKeyObject.h"
#include "JSPublicKeyObject.h"
#include "JSPrivateKeyObject.h"
#include "CryptoKeyType.h"
#include "JSNodePerformanceHooksHistogram.h"
#include "../napi.h"
#include <limits>
#include <algorithm>
#if USE(CG)
#include <CoreGraphics/CoreGraphics.h>
#endif
#if PLATFORM(COCOA)
#include <CoreFoundation/CoreFoundation.h>
#endif
#if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS)
#include "JSOffscreenCanvas.h"
#include "OffscreenCanvas.h"
#endif
#if CPU(BIG_ENDIAN) || CPU(MIDDLE_ENDIAN) || CPU(NEEDS_ALIGNED_ACCESS)
#define ASSUME_LITTLE_ENDIAN 0
#else
#define ASSUME_LITTLE_ENDIAN 1
#endif
namespace WebCore {
using namespace JSC;
using namespace Bun;
DEFINE_ALLOCATOR_WITH_HEAP_IDENTIFIER(SerializedScriptValue);
static constexpr unsigned maximumFilterRecursion = 40000;
static constexpr uint64_t autoLengthMarker = UINT64_MAX;
enum class SerializationReturnCode {
SuccessfullyCompleted,
StackOverflowError,
InterruptedExecutionError,
ValidationError,
ExistingExceptionError,
DataCloneError,
UnspecifiedError
};
enum WalkerState { StateUnknown,
ArrayStartState,
ArrayStartVisitMember,
ArrayEndVisitMember,
ObjectStartState,
ObjectStartVisitMember,
ObjectEndVisitMember,
MapDataStartVisitEntry,
MapDataEndVisitKey,
MapDataEndVisitValue,
SetDataStartVisitEntry,
SetDataEndVisitKey };
// These can't be reordered, and any new types must be added to the end of the list
// When making changes to these lists please cover your new type(s) in the API test "IndexedDB.StructuredCloneBackwardCompatibility"
enum SerializationTag {
ArrayTag = 1,
ObjectTag = 2,
UndefinedTag = 3,
NullTag = 4,
IntTag = 5,
ZeroTag = 6,
OneTag = 7,
FalseTag = 8,
TrueTag = 9,
DoubleTag = 10,
DateTag = 11,
FileTag = 12,
FileListTag = 13,
ImageDataTag = 14,
BlobTag = 15,
StringTag = 16,
EmptyStringTag = 17,
RegExpTag = 18,
ObjectReferenceTag = 19,
MessagePortReferenceTag = 20,
ArrayBufferTag = 21,
ArrayBufferViewTag = 22,
ArrayBufferTransferTag = 23,
TrueObjectTag = 24,
FalseObjectTag = 25,
StringObjectTag = 26,
EmptyStringObjectTag = 27,
NumberObjectTag = 28,
SetObjectTag = 29,
MapObjectTag = 30,
NonMapPropertiesTag = 31,
NonSetPropertiesTag = 32,
#if ENABLE(WEB_CRYPTO)
CryptoKeyTag = 33,
#endif
SharedArrayBufferTag = 34,
#if ENABLE(WEBASSEMBLY)
WasmModuleTag = 35,
#endif
DOMPointReadOnlyTag = 36,
DOMPointTag = 37,
DOMRectReadOnlyTag = 38,
DOMRectTag = 39,
DOMMatrixReadOnlyTag = 40,
DOMMatrixTag = 41,
DOMQuadTag = 42,
ImageBitmapTransferTag = 43,
#if ENABLE(WEB_RTC)
RTCCertificateTag = 44,
#endif
ImageBitmapTag = 45,
#if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS)
OffscreenCanvasTransferTag = 46,
#endif
BigIntTag = 47,
BigIntObjectTag = 48,
#if ENABLE(WEBASSEMBLY)
WasmMemoryTag = 49,
#endif
#if ENABLE(WEB_RTC)
RTCDataChannelTransferTag = 50,
#endif
DOMExceptionTag = 51,
#if ENABLE(WEB_CODECS)
WebCodecsEncodedVideoChunkTag = 52,
WebCodecsVideoFrameTag = 53,
#endif
ResizableArrayBufferTag = 54,
ErrorInstanceTag = 55,
Bun__BlobTag = 254,
// bun types start at 254 and decrease with each addition
Bun__X509CertificateTag = 253,
Bun__KeyObjectTag = 252,
Bun__nodenet_BlockList = 251,
Bun__NodePerformanceHooksHistogramTag = 250,
ErrorTag = 255
};
enum ArrayBufferViewSubtag {
DataViewTag = 0,
Int8ArrayTag = 1,
Uint8ArrayTag = 2,
Uint8ClampedArrayTag = 3,
Int16ArrayTag = 4,
Uint16ArrayTag = 5,
Int32ArrayTag = 6,
Uint32ArrayTag = 7,
Float32ArrayTag = 8,
Float64ArrayTag = 9,
BigInt64ArrayTag = 10,
BigUint64ArrayTag = 11,
Float16ArrayTag = 12,
};
// static bool isTypeExposedToGlobalObject(JSC::JSGlobalObject& globalObject, SerializationTag tag)
// {
// #if ENABLE(WEB_AUDIO)
// if (!jsDynamicCast<JSAudioWorkletGlobalScope*>(&globalObject))
// return true;
// // Only built-in JS types are exposed to audio worklets.
// switch (tag) {
// case ArrayTag:
// case ObjectTag:
// case UndefinedTag:
// case NullTag:
// case IntTag:
// case ZeroTag:
// case OneTag:
// case FalseTag:
// case TrueTag:
// case DoubleTag:
// case DateTag:
// case StringTag:
// case EmptyStringTag:
// case RegExpTag:
// case ObjectReferenceTag:
// case ArrayBufferTag:
// case ArrayBufferViewTag:
// case ArrayBufferTransferTag:
// case TrueObjectTag:
// case FalseObjectTag:
// case StringObjectTag:
// case EmptyStringObjectTag:
// case NumberObjectTag:
// case SetObjectTag:
// case MapObjectTag:
// case NonMapPropertiesTag:
// case NonSetPropertiesTag:
// case SharedArrayBufferTag:
// #if ENABLE(WEBASSEMBLY)
// case WasmModuleTag:
// #endif
// case BigIntTag:
// case BigIntObjectTag:
// #if ENABLE(WEBASSEMBLY)
// case WasmMemoryTag:
// #endif
// case ResizableArrayBufferTag:
// case ErrorInstanceTag:
// case ErrorTag:
// case MessagePortReferenceTag:
// return true;
// case FileTag:
// case FileListTag:
// case ImageDataTag:
// case BlobTag:
// #if ENABLE(WEB_CRYPTO)
// case CryptoKeyTag:
// #endif
// case DOMPointReadOnlyTag:
// case DOMPointTag:
// case DOMRectReadOnlyTag:
// case DOMRectTag:
// case DOMMatrixReadOnlyTag:
// case DOMMatrixTag:
// case DOMQuadTag:
// case ImageBitmapTransferTag:
// #if ENABLE(WEB_RTC)
// case RTCCertificateTag:
// #endif
// case ImageBitmapTag:
// #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS)
// case OffscreenCanvasTransferTag:
// #endif
// #if ENABLE(WEB_RTC)
// case RTCDataChannelTransferTag:
// #endif
// case DOMExceptionTag:
// #if ENABLE(WEB_CODECS)
// case WebCodecsEncodedVideoChunkTag:
// case WebCodecsVideoFrameTag:
// #endif
// break;
// }
// return false;
// #else
// UNUSED_PARAM(globalObject);
// UNUSED_PARAM(tag);
// return true;
// #endif
// }
static unsigned typedArrayElementSize(ArrayBufferViewSubtag tag)
{
switch (tag) {
case DataViewTag:
case Int8ArrayTag:
case Uint8ArrayTag:
case Uint8ClampedArrayTag:
return 1;
case Int16ArrayTag:
case Uint16ArrayTag:
case Float16ArrayTag:
return 2;
case Int32ArrayTag:
case Uint32ArrayTag:
case Float32ArrayTag:
return 4;
case Float64ArrayTag:
case BigInt64ArrayTag:
case BigUint64ArrayTag:
return 8;
default:
return 0;
}
}
enum class SerializableErrorType : uint8_t {
Error,
EvalError,
RangeError,
ReferenceError,
SyntaxError,
TypeError,
URIError,
Last = URIError
};
static SerializableErrorType errorNameToSerializableErrorType(const String& name)
{
if (equalLettersIgnoringASCIICase(name, "evalerror"_s))
return SerializableErrorType::EvalError;
if (equalLettersIgnoringASCIICase(name, "rangeerror"_s))
return SerializableErrorType::RangeError;
if (equalLettersIgnoringASCIICase(name, "referenceerror"_s))
return SerializableErrorType::ReferenceError;
if (equalLettersIgnoringASCIICase(name, "syntaxerror"_s))
return SerializableErrorType::SyntaxError;
if (equalLettersIgnoringASCIICase(name, "typeerror"_s))
return SerializableErrorType::TypeError;
if (equalLettersIgnoringASCIICase(name, "urierror"_s))
return SerializableErrorType::URIError;
return SerializableErrorType::Error;
}
static ErrorType toErrorType(SerializableErrorType value)
{
switch (value) {
case SerializableErrorType::Error:
return ErrorType::Error;
case SerializableErrorType::EvalError:
return ErrorType::EvalError;
case SerializableErrorType::RangeError:
return ErrorType::RangeError;
case SerializableErrorType::ReferenceError:
return ErrorType::ReferenceError;
case SerializableErrorType::SyntaxError:
return ErrorType::SyntaxError;
case SerializableErrorType::TypeError:
return ErrorType::TypeError;
case SerializableErrorType::URIError:
return ErrorType::URIError;
}
return ErrorType::Error;
}
enum class PredefinedColorSpaceTag : uint8_t {
SRGB = 0
#if ENABLE(PREDEFINED_COLOR_SPACE_DISPLAY_P3)
,
DisplayP3 = 1
#endif
};
enum DestinationColorSpaceTag {
DestinationColorSpaceSRGBTag = 0,
#if ENABLE(DESTINATION_COLOR_SPACE_LINEAR_SRGB)
DestinationColorSpaceLinearSRGBTag = 1,
#endif
#if ENABLE(DESTINATION_COLOR_SPACE_DISPLAY_P3)
DestinationColorSpaceDisplayP3Tag = 2,
#endif
#if PLATFORM(COCOA)
DestinationColorSpaceCGColorSpaceNameTag = 3,
DestinationColorSpaceCGColorSpacePropertyListTag = 4,
#endif
};
#if ENABLE(WEBASSEMBLY)
static String agentClusterIDFromGlobalObject(JSGlobalObject& globalObject)
{
if (!globalObject.inherits<JSDOMGlobalObject>())
return JSDOMGlobalObject::defaultAgentClusterID();
return jsCast<JSDOMGlobalObject*>(&globalObject)->agentClusterID();
}
#endif
#if ENABLE(WEB_CRYPTO)
const uint32_t currentKeyFormatVersion = 1;
enum class CryptoKeyClassSubtag {
HMAC = 0,
AES = 1,
RSA = 2,
EC = 3,
Raw = 4,
OKP = 5,
};
const uint8_t cryptoKeyClassSubtagMaximumValue = 5;
enum class CryptoKeyAsymmetricTypeSubtag {
Public = 0,
Private = 1
};
const uint8_t cryptoKeyAsymmetricTypeSubtagMaximumValue = 1;
enum class CryptoKeyUsageTag {
Encrypt = 0,
Decrypt = 1,
Sign = 2,
Verify = 3,
DeriveKey = 4,
DeriveBits = 5,
WrapKey = 6,
UnwrapKey = 7
};
const uint8_t cryptoKeyUsageTagMaximumValue = 7;
enum class CryptoAlgorithmIdentifierTag {
RSAES_PKCS1_v1_5 = 0,
RSASSA_PKCS1_v1_5 = 1,
RSA_PSS = 2,
RSA_OAEP = 3,
ECDSA = 4,
ECDH = 5,
AES_CTR = 6,
AES_CBC = 7,
AES_GCM = 9,
AES_CFB = 10,
AES_KW = 11,
HMAC = 12,
SHA_1 = 14,
SHA_224 = 15,
SHA_256 = 16,
SHA_384 = 17,
SHA_512 = 18,
HKDF = 20,
PBKDF2 = 21,
ED25519 = 22,
X25519 = 23,
};
const uint8_t cryptoAlgorithmIdentifierTagMaximumValue = 22;
static unsigned countUsages(CryptoKeyUsageBitmap usages)
{
// Fast bit count algorithm for sparse bit maps.
unsigned count = 0;
while (usages) {
usages = usages & (usages - 1);
++count;
}
return count;
}
enum class CryptoKeyOKPOpNameTag {
X25519 = 0,
ED25519 = 1,
};
const uint8_t cryptoKeyOKPOpNameTagMaximumValue = 1;
#endif
/* CurrentVersion tracks the serialization version so that persistent stores
* are able to correctly bail out in the case of encountering newer formats.
*
* Initial version was 1.
* Version 2. added the ObjectReferenceTag and support for serialization of cyclic graphs.
* Version 3. added the FalseObjectTag, TrueObjectTag, NumberObjectTag, StringObjectTag
* and EmptyStringObjectTag for serialization of Boolean, Number and String objects.
* Version 4. added support for serializing non-index properties of arrays.
* Version 5. added support for Map and Set types.
* Version 6. added support for 8-bit strings.
* Version 7. added support for File's lastModified attribute.
* Version 8. added support for ImageData's colorSpace attribute.
* Version 9. added support for ImageBitmap color space.
* Version 10. changed the length (and offsets) of ArrayBuffers (and ArrayBufferViews) from 32 to 64 bits.
* Version 11. added support for Blob's memory cost.
* Version 12. added support for agent cluster ID.
* Version 13. added support for ErrorInstance objects.
*/
[[maybe_unused]] static constexpr unsigned CurrentVersion = 13;
[[maybe_unused]] static constexpr unsigned TerminatorTag = 0xFFFFFFFF;
[[maybe_unused]] static constexpr unsigned StringPoolTag = 0xFFFFFFFE;
[[maybe_unused]] static constexpr unsigned NonIndexPropertiesTag = 0xFFFFFFFD;
[[maybe_unused]] static constexpr uint32_t ImageDataPoolTag = 0xFFFFFFFE;
// The high bit of a StringData's length determines the character size.
static constexpr unsigned StringDataIs8BitFlag = 0x80000000;
/*
* Object serialization is performed according to the following grammar, all tags
* are recorded as a single uint8_t.
*
* IndexType (used for the object pool and StringData's constant pool) is the
* minimum sized unsigned integer type required to represent the maximum index
* in the constant pool.
*
* SerializedValue :- <CurrentVersion:uint32_t> Value
* Value :- Array | Object | Map | Set | Terminal
*
* Array :-
* ArrayTag <length:uint32_t>(<index:uint32_t><value:Value>)* TerminatorTag
*
* Object :-
* ObjectTag (<name:StringData><value:Value>)* TerminatorTag
*
* Map :- MapObjectTag MapData
*
* Set :- SetObjectTag SetData
*
* MapData :- (<key:Value><value:Value>)* NonMapPropertiesTag (<name:StringData><value:Value>)* TerminatorTag
* SetData :- (<key:Value>)* NonSetPropertiesTag (<name:StringData><value:Value>)* TerminatorTag
*
* Terminal :-
* UndefinedTag
* | NullTag
* | IntTag <value:int32_t>
* | ZeroTag
* | OneTag
* | FalseTag
* | TrueTag
* | FalseObjectTag
* | TrueObjectTag
* | DoubleTag <value:double>
* | NumberObjectTag <value:double>
* | DateTag <value:double>
* | String
* | EmptyStringTag
* | EmptyStringObjectTag
* | BigInt
* | File
* | FileList
* | ImageData
* | Blob
* | ObjectReference
* | MessagePortReferenceTag <value:uint32_t>
* | ArrayBuffer
* | ArrayBufferViewTag ArrayBufferViewSubtag <byteOffset:uint64_t> <byteLength:uint64_t> (ArrayBuffer | ObjectReference)
* | CryptoKeyTag <wrappedKeyLength:uint32_t> <factor:byte{wrappedKeyLength}>
* | DOMPoint
* | DOMRect
* | DOMMatrix
* | DOMQuad
* | ImageBitmapTransferTag <value:uint32_t>
* | RTCCertificateTag
* | ImageBitmapTag <originClean:uint8_t> <logicalWidth:int32_t> <logicalHeight:int32_t> <resolutionScale:double> DestinationColorSpace <byteLength:uint32_t>(<imageByteData:uint8_t>)
* | OffscreenCanvasTransferTag <value:uint32_t>
* | WasmMemoryTag <value:uint32_t>
* | RTCDataChannelTransferTag <identifier:uint32_t>
* | DOMExceptionTag <message:String> <name:String>
* | WebCodecsEncodedVideoChunkTag <identifier:uint32_t>
*
* Inside certificate, data is serialized in this format as per spec:
*
* <expires:double> <certificate:StringData> <origin:StringData> <keyingMaterial:StringData>
* We also add fingerprints to make sure we expose to JavaScript the same information.
*
* Inside wrapped crypto key, data is serialized in this format:
*
* <keyFormatVersion:uint32_t> <extractable:int32_t> <usagesCount:uint32_t> <usages:byte{usagesCount}> CryptoKeyClassSubtag (CryptoKeyHMAC | CryptoKeyAES | CryptoKeyRSA)
*
* String :-
* EmptyStringTag
* StringTag StringData
*
* StringObject:
* EmptyStringObjectTag
* StringObjectTag StringData
*
* StringData :-
* StringPoolTag <cpIndex:IndexType>
* (not (TerminatorTag | StringPoolTag))<is8Bit:uint32_t:1><length:uint32_t:31><characters:CharType{length}> // Added to constant pool when seen, string length 0xFFFFFFFF is disallowed
*
* BigInt :-
* BigIntTag BigIntData
* BigIntObjectTag BigIntData
*
* BigIntData :-
* <sign:uint8_t> <lengthInUint64:uint32_t> <contents:uint64_t{lengthInUint64}>
*
* File :-
* FileTag FileData
*
* FileData :-
* <path:StringData> <url:StringData> <type:StringData> <name:StringData> <lastModified:double>
*
* FileList :-
* FileListTag <length:uint32_t>(<file:FileData>){length}
*
* ImageData :-
* ImageDataTag <width:int32_t> <height:int32_t> <length:uint32_t> <data:uint8_t{length}> <colorSpace:PredefinedColorSpaceTag>
*
* Blob :-
* BlobTag <url:StringData><type:StringData><size:long long><memoryCost:long long>
*
* RegExp :-
* RegExpTag <pattern:StringData><flags:StringData>
*
* ObjectReference :-
* ObjectReferenceTag <opIndex:IndexType>
*
* ArrayBuffer :-
* ArrayBufferTag <byteLength:uint64_t> <contents:byte{length}>
* ResizableArrayBufferTag <byteLength:uint64_t> <maxLength:uint64_t> <contents:byte{length}>
* ArrayBufferTransferTag <value:uint32_t>
* SharedArrayBufferTag <value:uint32_t>
*
* CryptoKeyHMAC :-
* <keySize:uint32_t> <keyData:byte{keySize}> CryptoAlgorithmIdentifierTag // Algorithm tag inner hash function.
*
* CryptoKeyAES :-
* CryptoAlgorithmIdentifierTag <keySize:uint32_t> <keyData:byte{keySize}>
*
* CryptoKeyRSA :-
* CryptoAlgorithmIdentifierTag <isRestrictedToHash:int32_t> CryptoAlgorithmIdentifierTag? CryptoKeyAsymmetricTypeSubtag CryptoKeyRSAPublicComponents CryptoKeyRSAPrivateComponents?
*
* CryptoKeyRSAPublicComponents :-
* <modulusSize:uint32_t> <modulus:byte{modulusSize}> <exponentSize:uint32_t> <exponent:byte{exponentSize}>
*
* CryptoKeyRSAPrivateComponents :-
* <privateExponentSize:uint32_t> <privateExponent:byte{privateExponentSize}> <primeCount:uint32_t> FirstPrimeInfo? PrimeInfo{primeCount - 1}
*
* // CRT data could be computed from prime factors. It is only serialized to reuse a code path that's needed for JWK.
* FirstPrimeInfo :-
* <factorSize:uint32_t> <factor:byte{factorSize}> <crtExponentSize:uint32_t> <crtExponent:byte{crtExponentSize}>
*
* PrimeInfo :-
* <factorSize:uint32_t> <factor:byte{factorSize}> <crtExponentSize:uint32_t> <crtExponent:byte{crtExponentSize}> <crtCoefficientSize:uint32_t> <crtCoefficient:byte{crtCoefficientSize}>
*
* CryptoKeyEC :-
* CryptoAlgorithmIdentifierTag <namedCurve:StringData> CryptoKeyAsymmetricTypeSubtag <keySize:uint32_t> <keyData:byte{keySize}>
*
* CryptoKeyRaw :-
* CryptoAlgorithmIdentifierTag <keySize:uint32_t> <keyData:byte{keySize}>
*
* DOMPoint :-
* DOMPointReadOnlyTag DOMPointData
* | DOMPointTag DOMPointData
*
* DOMPointData :-
* <x:double> <y:double> <z:double> <w:double>
*
* DOMRect :-
* DOMRectReadOnlyTag DOMRectData
* | DOMRectTag DOMRectData
*
* DOMRectData :-
* <x:double> <y:double> <width:double> <height:double>
*
* DOMMatrix :-
* DOMMatrixReadOnlyTag DOMMatrixData
* | DOMMatrixTag DOMMatrixData
*
* DOMMatrixData :-
* <is2D:uint8_t:true> <m11:double> <m12:double> <m21:double> <m22:double> <m41:double> <m42:double>
* | <is2D:uint8_t:false> <m11:double> <m12:double> <m13:double> <m14:double> <m21:double> <m22:double> <m23:double> <m24:double> <m31:double> <m32:double> <m33:double> <m34:double> <m41:double> <m42:double> <m43:double> <m44:double>
*
* DOMQuad :-
* DOMQuadTag DOMQuadData
*
* DOMQuadData :-
* <p1:DOMPointData> <p2:DOMPointData> <p3:DOMPointData> <p4:DOMPointData>
*
* DestinationColorSpace :-
* DestinationColorSpaceSRGBTag
* | DestinationColorSpaceLinearSRGBTag
* | DestinationColorSpaceDisplayP3Tag
* | DestinationColorSpaceCGColorSpaceNameTag <nameDataLength:uint32_t> <nameData:uint8_t>{nameDataLength}
* | DestinationColorSpaceCGColorSpacePropertyListTag <propertyListDataLength:uint32_t> <propertyListData:uint8_t>{propertyListDataLength}
*/
using DeserializationResult = std::pair<JSC::JSValue, SerializationReturnCode>;
class CloneBase {
WTF_FORBID_HEAP_ALLOCATION;
protected:
CloneBase(JSGlobalObject* lexicalGlobalObject)
: m_lexicalGlobalObject(lexicalGlobalObject)
, m_failed(false)
{
}
void fail()
{
m_failed = true;
}
JSGlobalObject* const m_lexicalGlobalObject;
bool m_failed;
MarkedArgumentBuffer m_gcBuffer;
};
#if ENABLE(WEB_CRYPTO)
static bool wrapCryptoKey(JSGlobalObject* lexicalGlobalObject, const Vector<uint8_t>& key, Vector<uint8_t>& wrappedKey)
{
auto context = executionContext(lexicalGlobalObject);
return context && context->wrapCryptoKey(key, wrappedKey);
}
static bool unwrapCryptoKey(JSGlobalObject* lexicalGlobalObject, const Vector<uint8_t>& wrappedKey, Vector<uint8_t>& key)
{
auto context = executionContext(lexicalGlobalObject);
return context && context->unwrapCryptoKey(wrappedKey, key);
}
#endif
#if ASSUME_LITTLE_ENDIAN
template<typename T> static void writeLittleEndian(Vector<uint8_t>& buffer, T value)
{
buffer.append(std::span { reinterpret_cast<uint8_t*>(&value), sizeof(value) });
}
#else
template<typename T> static void writeLittleEndian(Vector<uint8_t>& buffer, T value)
{
for (unsigned i = 0; i < sizeof(T); i++) {
buffer.append(value & 0xFF);
value >>= 8;
}
}
#endif
template<> void writeLittleEndian<uint8_t>(Vector<uint8_t>& buffer, uint8_t value)
{
buffer.append(value);
}
template<typename T> static bool writeLittleEndian(Vector<uint8_t>& buffer, const T* values, uint32_t length)
{
if (length > std::numeric_limits<uint32_t>::max() / sizeof(T))
return false;
#if ASSUME_LITTLE_ENDIAN
buffer.append(std::span { reinterpret_cast<const uint8_t*>(values), length * sizeof(T) });
#else
for (unsigned i = 0; i < length; i++) {
T value = values[i];
for (unsigned j = 0; j < sizeof(T); j++) {
buffer.append(static_cast<uint8_t>(value & 0xFF));
value >>= 8;
}
}
#endif
return true;
}
template<> bool writeLittleEndian<uint8_t>(Vector<uint8_t>& buffer, const uint8_t* values, uint32_t length)
{
buffer.append(std::span { values, length });
return true;
}
class CloneSerializer : public CloneBase {
WTF_FORBID_HEAP_ALLOCATION;
public:
Vector<uint8_t>& m_buffer;
void write(const uint8_t* data, unsigned length)
{
writeLittleEndian(m_buffer, data, length);
}
// static SerializationReturnCode serialize(JSGlobalObject* lexicalGlobalObject, JSValue value, Vector<RefPtr<MessagePort>>& messagePorts, Vector<RefPtr<JSC::ArrayBuffer>>& arrayBuffers, const Vector<RefPtr<ImageBitmap>>& imageBitmaps,
// #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS)
// const Vector<RefPtr<OffscreenCanvas>>& offscreenCanvases,
// #endif
// #if ENABLE(WEB_RTC)
// const Vector<Ref<RTCDataChannel>>& rtcDataChannels,
// #endif
// #if ENABLE(WEB_CODECS)
// Vector<RefPtr<WebCodecsEncodedVideoChunkStorage>>& serializedVideoChunks,
// Vector<RefPtr<WebCodecsVideoFrame>>& serializedVideoFrames,
// #endif
// #if ENABLE(WEBASSEMBLY)
// WasmModuleArray& wasmModules,
// WasmMemoryHandleArray& wasmMemoryHandles,
// #endif
// Vector<URLKeepingBlobAlive>& blobHandles, Vector<uint8_t>& out, SerializationContext context, ArrayBufferContentsArray& sharedBuffers,
// SerializationForStorage forStorage)
// {
// CloneSerializer serializer(lexicalGlobalObject, messagePorts, arrayBuffers, imageBitmaps,
// #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS)
// offscreenCanvases,
// #endif
// #if ENABLE(WEB_RTC)
// rtcDataChannels,
// #endif
// #if ENABLE(WEB_CODECS)
// serializedVideoChunks,
// serializedVideoFrames,
// #endif
// #if ENABLE(WEBASSEMBLY)
// wasmModules,
// wasmMemoryHandles,
// #endif
// blobHandles, out, context, sharedBuffers, forStorage);
// return serializer.serialize(value);
// }
static SerializationReturnCode serialize(JSGlobalObject* lexicalGlobalObject, JSValue value, Vector<RefPtr<MessagePort>>& messagePorts, Vector<RefPtr<JSC::ArrayBuffer>>& arrayBuffers,
#if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS)
const Vector<RefPtr<OffscreenCanvas>>& offscreenCanvases,
#endif
#if ENABLE(WEB_RTC)
const Vector<Ref<RTCDataChannel>>& rtcDataChannels,
#endif
#if ENABLE(WEB_CODECS)
Vector<RefPtr<WebCodecsEncodedVideoChunkStorage>>& serializedVideoChunks,
Vector<RefPtr<WebCodecsVideoFrame>>& serializedVideoFrames,
#endif
#if ENABLE(WEBASSEMBLY)
WasmModuleArray& wasmModules,
WasmMemoryHandleArray& wasmMemoryHandles,
#endif
Vector<uint8_t>& out, SerializationContext context, ArrayBufferContentsArray& sharedBuffers,
SerializationForStorage forStorage, SerializationForCrossProcessTransfer forTransfer)
{
CloneSerializer serializer(lexicalGlobalObject, messagePorts, arrayBuffers,
#if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS)
offscreenCanvases,
#endif
#if ENABLE(WEB_RTC)
rtcDataChannels,
#endif
#if ENABLE(WEB_CODECS)
serializedVideoChunks,
serializedVideoFrames,
#endif
#if ENABLE(WEBASSEMBLY)
wasmModules,
wasmMemoryHandles,
#endif
out, context, sharedBuffers, forStorage, forTransfer);
return serializer.serialize(value);
}
static bool serialize(StringView string, Vector<uint8_t>& out)
{
writeLittleEndian(out, CurrentVersion);
if (string.isEmpty()) {
writeLittleEndian<uint8_t>(out, EmptyStringTag);
return true;
}
writeLittleEndian<uint8_t>(out, StringTag);
const auto length = string.length();
if (string.is8Bit()) {
const auto span = string.span8();
writeLittleEndian(out, length | StringDataIs8BitFlag);
return writeLittleEndian(out, span.data(), length);
}
const auto span = string.span16();
writeLittleEndian(out, length);
return writeLittleEndian(out, span.data(), length);
}
private:
typedef HashMap<JSObject*, uint32_t> ObjectPool;
// CloneSerializer(JSGlobalObject* lexicalGlobalObject, Vector<RefPtr<MessagePort>>& messagePorts, Vector<RefPtr<JSC::ArrayBuffer>>& arrayBuffers, const Vector<RefPtr<ImageBitmap>>& imageBitmaps,
// #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS)
// const Vector<RefPtr<OffscreenCanvas>>& offscreenCanvases,
// #endif
// #if ENABLE(WEB_RTC)
// const Vector<Ref<RTCDataChannel>>& rtcDataChannels,
// #endif
// #if ENABLE(WEB_CODECS)
// Vector<RefPtr<WebCodecsEncodedVideoChunkStorage>>& serializedVideoChunks,
// Vector<RefPtr<WebCodecsVideoFrame>>& serializedVideoFrames,
// #endif
// #if ENABLE(WEBASSEMBLY)
// WasmModuleArray& wasmModules,
// WasmMemoryHandleArray& wasmMemoryHandles,
// #endif
// Vector<URLKeepingBlobAlive>& blobHandles, Vector<uint8_t>& out, SerializationContext context, ArrayBufferContentsArray& sharedBuffers, SerializationForStorage forStorage)
// : CloneBase(lexicalGlobalObject)
// , m_buffer(out)
// , m_blobHandles(blobHandles)
// , m_emptyIdentifier(Identifier::fromString(lexicalGlobalObject->vm(), emptyString()))
// , m_context(context)
// , m_sharedBuffers(sharedBuffers)
// #if ENABLE(WEBASSEMBLY)
// , m_wasmModules(wasmModules)
// , m_wasmMemoryHandles(wasmMemoryHandles)
// #endif
// #if ENABLE(WEB_CODECS)
// , m_serializedVideoChunks(serializedVideoChunks)
// , m_serializedVideoFrames(serializedVideoFrames)
// #endif
// , m_forStorage(forStorage)
// {
// write(CurrentVersion);
// fillTransferMap(messagePorts, m_transferredMessagePorts);
// fillTransferMap(arrayBuffers, m_transferredArrayBuffers);
// fillTransferMap(imageBitmaps, m_transferredImageBitmaps);
// #if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS)
// fillTransferMap(offscreenCanvases, m_transferredOffscreenCanvases);
// #endif
// #if ENABLE(WEB_RTC)
// fillTransferMap(rtcDataChannels, m_transferredRTCDataChannels);
// #endif
// }
CloneSerializer(JSGlobalObject* lexicalGlobalObject, Vector<RefPtr<MessagePort>>& messagePorts, Vector<RefPtr<JSC::ArrayBuffer>>& arrayBuffers,
#if ENABLE(OFFSCREEN_CANVAS_IN_WORKERS)
const Vector<RefPtr<OffscreenCanvas>>& offscreenCanvases,
#endif
#if ENABLE(WEB_RTC)
const Vector<Ref<RTCDataChannel>>& rtcDataChannels,
#endif
#if ENABLE(WEB_CODECS)
Vector<RefPtr<WebCodecsEncodedVideoChunkStorage>>& serializedVideoChunks,
Vector<RefPtr<WebCodecsVideoFrame>>& serializedVideoFrames,
#endif
#if ENABLE(WEBASSEMBLY)
WasmModuleArray& wasmModules,
WasmMemoryHandleArray& wasmMemoryHandles,
#endif