/
value-serializer.cc
2575 lines (2340 loc) Β· 91.2 KB
/
value-serializer.cc
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 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/objects/value-serializer.h"
#include <type_traits>
#include "include/v8-maybe.h"
#include "include/v8-value-serializer-version.h"
#include "include/v8-value-serializer.h"
#include "include/v8-wasm.h"
#include "src/api/api-inl.h"
#include "src/base/logging.h"
#include "src/base/platform/wrappers.h"
#include "src/execution/isolate.h"
#include "src/flags/flags.h"
#include "src/handles/global-handles-inl.h"
#include "src/handles/handles-inl.h"
#include "src/handles/maybe-handles-inl.h"
#include "src/heap/factory.h"
#include "src/numbers/conversions.h"
#include "src/objects/heap-number-inl.h"
#include "src/objects/js-array-buffer-inl.h"
#include "src/objects/js-array-inl.h"
#include "src/objects/js-collection-inl.h"
#include "src/objects/js-regexp-inl.h"
#include "src/objects/js-struct-inl.h"
#include "src/objects/map-updater.h"
#include "src/objects/objects-inl.h"
#include "src/objects/objects.h"
#include "src/objects/oddball-inl.h"
#include "src/objects/ordered-hash-table-inl.h"
#include "src/objects/property-descriptor.h"
#include "src/objects/property-details.h"
#include "src/objects/smi.h"
#include "src/objects/transitions-inl.h"
#include "src/snapshot/code-serializer.h"
#if V8_ENABLE_WEBASSEMBLY
#include "src/wasm/wasm-objects-inl.h"
#endif // V8_ENABLE_WEBASSEMBLY
namespace v8 {
namespace internal {
// Version 9: (imported from Blink)
// Version 10: one-byte (Latin-1) strings
// Version 11: properly separate undefined from the hole in arrays
// Version 12: regexp and string objects share normal string encoding
// Version 13: host objects have an explicit tag (rather than handling all
// unknown tags)
// Version 14: flags for JSArrayBufferViews
// Version 15: support for shared objects with an explicit tag
//
// WARNING: Increasing this value is a change which cannot safely be rolled
// back without breaking compatibility with data stored on disk. It is
// strongly recommended that you do not make such changes near a release
// milestone branch point.
//
// Recent changes are routinely reverted in preparation for branch, and this
// has been the cause of at least one bug in the past.
static const uint32_t kLatestVersion = 15;
static_assert(kLatestVersion == v8::CurrentValueSerializerFormatVersion(),
"Exported format version must match latest version.");
namespace {
// For serializing JSArrayBufferView flags. Instead of serializing /
// deserializing the flags directly, we serialize them bit by bit. This is for
// ensuring backwards compatilibity in the case where the representation
// changes. Note that the ValueSerializer data can be stored on disk.
using JSArrayBufferViewIsLengthTracking = base::BitField<bool, 0, 1>;
using JSArrayBufferViewIsBackedByRab =
JSArrayBufferViewIsLengthTracking::Next<bool, 1>;
} // namespace
template <typename T>
static size_t BytesNeededForVarint(T value) {
static_assert(std::is_integral<T>::value && std::is_unsigned<T>::value,
"Only unsigned integer types can be written as varints.");
size_t result = 0;
do {
result++;
value >>= 7;
} while (value);
return result;
}
enum class SerializationTag : uint8_t {
// version:uint32_t (if at beginning of data, sets version > 0)
kVersion = 0xFF,
// ignore
kPadding = '\0',
// refTableSize:uint32_t (previously used for sanity checks; safe to ignore)
kVerifyObjectCount = '?',
// Oddballs (no data).
kTheHole = '-',
kUndefined = '_',
kNull = '0',
kTrue = 'T',
kFalse = 'F',
// Number represented as 32-bit integer, ZigZag-encoded
// (like sint32 in protobuf)
kInt32 = 'I',
// Number represented as 32-bit unsigned integer, varint-encoded
// (like uint32 in protobuf)
kUint32 = 'U',
// Number represented as a 64-bit double.
// Host byte order is used (N.B. this makes the format non-portable).
kDouble = 'N',
// BigInt. Bitfield:uint32_t, then raw digits storage.
kBigInt = 'Z',
// byteLength:uint32_t, then raw data
kUtf8String = 'S',
kOneByteString = '"',
kTwoByteString = 'c',
// Reference to a serialized object. objectID:uint32_t
kObjectReference = '^',
// Beginning of a JS object.
kBeginJSObject = 'o',
// End of a JS object. numProperties:uint32_t
kEndJSObject = '{',
// Beginning of a sparse JS array. length:uint32_t
// Elements and properties are written as key/value pairs, like objects.
kBeginSparseJSArray = 'a',
// End of a sparse JS array. numProperties:uint32_t length:uint32_t
kEndSparseJSArray = '@',
// Beginning of a dense JS array. length:uint32_t
// |length| elements, followed by properties as key/value pairs
kBeginDenseJSArray = 'A',
// End of a dense JS array. numProperties:uint32_t length:uint32_t
kEndDenseJSArray = '$',
// Date. millisSinceEpoch:double
kDate = 'D',
// Boolean object. No data.
kTrueObject = 'y',
kFalseObject = 'x',
// Number object. value:double
kNumberObject = 'n',
// BigInt object. Bitfield:uint32_t, then raw digits storage.
kBigIntObject = 'z',
// String object, UTF-8 encoding. byteLength:uint32_t, then raw data.
kStringObject = 's',
// Regular expression, UTF-8 encoding. byteLength:uint32_t, raw data,
// flags:uint32_t.
kRegExp = 'R',
// Beginning of a JS map.
kBeginJSMap = ';',
// End of a JS map. length:uint32_t.
kEndJSMap = ':',
// Beginning of a JS set.
kBeginJSSet = '\'',
// End of a JS set. length:uint32_t.
kEndJSSet = ',',
// Array buffer. byteLength:uint32_t, then raw data.
kArrayBuffer = 'B',
// Array buffer (transferred). transferID:uint32_t
kArrayBufferTransfer = 't',
// View into an array buffer.
// subtag:ArrayBufferViewTag, byteOffset:uint32_t, byteLength:uint32_t
// For typed arrays, byteOffset and byteLength must be divisible by the size
// of the element.
// Note: kArrayBufferView is special, and should have an ArrayBuffer (or an
// ObjectReference to one) serialized just before it. This is a quirk arising
// from the previous stack-based implementation.
kArrayBufferView = 'V',
// Shared array buffer. transferID:uint32_t
kSharedArrayBuffer = 'u',
// A HeapObject shared across Isolates. sharedValueID:uint32_t
kSharedObject = 'p',
// A wasm module object transfer. next value is its index.
kWasmModuleTransfer = 'w',
// The delegate is responsible for processing all following data.
// This "escapes" to whatever wire format the delegate chooses.
kHostObject = '\\',
// A transferred WebAssembly.Memory object. maximumPages:int32_t, then by
// SharedArrayBuffer tag and its data.
kWasmMemoryTransfer = 'm',
// A list of (subtag: ErrorTag, [subtag dependent data]). See ErrorTag for
// details.
kError = 'r',
// The following tags are reserved because they were in use in Chromium before
// the kHostObject tag was introduced in format version 13, at
// v8 refs/heads/master@{#43466}
// chromium/src refs/heads/master@{#453568}
//
// They must not be reused without a version check to prevent old values from
// starting to deserialize incorrectly. For simplicity, it's recommended to
// avoid them altogether.
//
// This is the set of tags that existed in SerializationTag.h at that time and
// still exist at the time of this writing (i.e., excluding those that were
// removed on the Chromium side because there should be no real user data
// containing them).
//
// It might be possible to also free up other tags which were never persisted
// (e.g. because they were used only for transfer) in the future.
kLegacyReservedMessagePort = 'M',
kLegacyReservedBlob = 'b',
kLegacyReservedBlobIndex = 'i',
kLegacyReservedFile = 'f',
kLegacyReservedFileIndex = 'e',
kLegacyReservedDOMFileSystem = 'd',
kLegacyReservedFileList = 'l',
kLegacyReservedFileListIndex = 'L',
kLegacyReservedImageData = '#',
kLegacyReservedImageBitmap = 'g',
kLegacyReservedImageBitmapTransfer = 'G',
kLegacyReservedOffscreenCanvas = 'H',
kLegacyReservedCryptoKey = 'K',
kLegacyReservedRTCCertificate = 'k',
};
namespace {
enum class ArrayBufferViewTag : uint8_t {
kInt8Array = 'b',
kUint8Array = 'B',
kUint8ClampedArray = 'C',
kInt16Array = 'w',
kUint16Array = 'W',
kInt32Array = 'd',
kUint32Array = 'D',
kFloat32Array = 'f',
kFloat64Array = 'F',
kBigInt64Array = 'q',
kBigUint64Array = 'Q',
kDataView = '?',
};
// Sub-tags only meaningful for error serialization.
enum class ErrorTag : uint8_t {
// The error is a EvalError. No accompanying data.
kEvalErrorPrototype = 'E',
// The error is a RangeError. No accompanying data.
kRangeErrorPrototype = 'R',
// The error is a ReferenceError. No accompanying data.
kReferenceErrorPrototype = 'F',
// The error is a SyntaxError. No accompanying data.
kSyntaxErrorPrototype = 'S',
// The error is a TypeError. No accompanying data.
kTypeErrorPrototype = 'T',
// The error is a URIError. No accompanying data.
kUriErrorPrototype = 'U',
// Followed by message: string.
kMessage = 'm',
// Followed by a JS object: cause.
kCause = 'c',
// Followed by stack: string.
kStack = 's',
// The end of this error information.
kEnd = '.',
};
} // namespace
ValueSerializer::ValueSerializer(Isolate* isolate,
v8::ValueSerializer::Delegate* delegate)
: isolate_(isolate),
delegate_(delegate),
supports_shared_values_(delegate && delegate->SupportsSharedValues()),
zone_(isolate->allocator(), ZONE_NAME),
id_map_(isolate->heap(), ZoneAllocationPolicy(&zone_)),
array_buffer_transfer_map_(isolate->heap(),
ZoneAllocationPolicy(&zone_)) {}
ValueSerializer::~ValueSerializer() {
if (buffer_) {
if (delegate_) {
delegate_->FreeBufferMemory(buffer_);
} else {
base::Free(buffer_);
}
}
}
void ValueSerializer::WriteHeader() {
WriteTag(SerializationTag::kVersion);
WriteVarint(kLatestVersion);
}
void ValueSerializer::SetTreatArrayBufferViewsAsHostObjects(bool mode) {
treat_array_buffer_views_as_host_objects_ = mode;
}
void ValueSerializer::WriteTag(SerializationTag tag) {
uint8_t raw_tag = static_cast<uint8_t>(tag);
WriteRawBytes(&raw_tag, sizeof(raw_tag));
}
template <typename T>
void ValueSerializer::WriteVarint(T value) {
// Writes an unsigned integer as a base-128 varint.
// The number is written, 7 bits at a time, from the least significant to the
// most significant 7 bits. Each byte, except the last, has the MSB set.
// See also https://developers.google.com/protocol-buffers/docs/encoding
static_assert(std::is_integral<T>::value && std::is_unsigned<T>::value,
"Only unsigned integer types can be written as varints.");
uint8_t stack_buffer[sizeof(T) * 8 / 7 + 1];
uint8_t* next_byte = &stack_buffer[0];
do {
*next_byte = (value & 0x7F) | 0x80;
next_byte++;
value >>= 7;
} while (value);
*(next_byte - 1) &= 0x7F;
WriteRawBytes(stack_buffer, next_byte - stack_buffer);
}
template <typename T>
void ValueSerializer::WriteZigZag(T value) {
// Writes a signed integer as a varint using ZigZag encoding (i.e. 0 is
// encoded as 0, -1 as 1, 1 as 2, -2 as 3, and so on).
// See also https://developers.google.com/protocol-buffers/docs/encoding
// Note that this implementation relies on the right shift being arithmetic.
static_assert(std::is_integral<T>::value && std::is_signed<T>::value,
"Only signed integer types can be written as zigzag.");
using UnsignedT = typename std::make_unsigned<T>::type;
WriteVarint((static_cast<UnsignedT>(value) << 1) ^
(value >> (8 * sizeof(T) - 1)));
}
template EXPORT_TEMPLATE_DEFINE(
V8_EXPORT_PRIVATE) void ValueSerializer::WriteZigZag(int32_t value);
void ValueSerializer::WriteDouble(double value) {
// Warning: this uses host endianness.
WriteRawBytes(&value, sizeof(value));
}
void ValueSerializer::WriteOneByteString(base::Vector<const uint8_t> chars) {
WriteVarint<uint32_t>(chars.length());
WriteRawBytes(chars.begin(), chars.length() * sizeof(uint8_t));
}
void ValueSerializer::WriteTwoByteString(base::Vector<const base::uc16> chars) {
// Warning: this uses host endianness.
WriteVarint<uint32_t>(chars.length() * sizeof(base::uc16));
WriteRawBytes(chars.begin(), chars.length() * sizeof(base::uc16));
}
void ValueSerializer::WriteBigIntContents(BigInt bigint) {
uint32_t bitfield = bigint.GetBitfieldForSerialization();
int bytelength = BigInt::DigitsByteLengthForBitfield(bitfield);
WriteVarint<uint32_t>(bitfield);
uint8_t* dest;
if (ReserveRawBytes(bytelength).To(&dest)) {
bigint.SerializeDigits(dest);
}
}
void ValueSerializer::WriteRawBytes(const void* source, size_t length) {
uint8_t* dest;
if (ReserveRawBytes(length).To(&dest) && length > 0) {
memcpy(dest, source, length);
}
}
Maybe<uint8_t*> ValueSerializer::ReserveRawBytes(size_t bytes) {
size_t old_size = buffer_size_;
size_t new_size = old_size + bytes;
if (V8_UNLIKELY(new_size > buffer_capacity_)) {
bool ok;
if (!ExpandBuffer(new_size).To(&ok)) {
return Nothing<uint8_t*>();
}
}
buffer_size_ = new_size;
return Just(&buffer_[old_size]);
}
Maybe<bool> ValueSerializer::ExpandBuffer(size_t required_capacity) {
DCHECK_GT(required_capacity, buffer_capacity_);
size_t requested_capacity =
std::max(required_capacity, buffer_capacity_ * 2) + 64;
size_t provided_capacity = 0;
void* new_buffer = nullptr;
if (delegate_) {
new_buffer = delegate_->ReallocateBufferMemory(buffer_, requested_capacity,
&provided_capacity);
} else {
new_buffer = base::Realloc(buffer_, requested_capacity);
provided_capacity = requested_capacity;
}
if (new_buffer) {
DCHECK(provided_capacity >= requested_capacity);
buffer_ = reinterpret_cast<uint8_t*>(new_buffer);
buffer_capacity_ = provided_capacity;
return Just(true);
} else {
out_of_memory_ = true;
return Nothing<bool>();
}
}
void ValueSerializer::WriteUint32(uint32_t value) {
WriteVarint<uint32_t>(value);
}
void ValueSerializer::WriteUint64(uint64_t value) {
WriteVarint<uint64_t>(value);
}
std::pair<uint8_t*, size_t> ValueSerializer::Release() {
auto result = std::make_pair(buffer_, buffer_size_);
buffer_ = nullptr;
buffer_size_ = 0;
buffer_capacity_ = 0;
return result;
}
void ValueSerializer::TransferArrayBuffer(uint32_t transfer_id,
Handle<JSArrayBuffer> array_buffer) {
DCHECK(!array_buffer_transfer_map_.Find(array_buffer));
DCHECK(!array_buffer->is_shared());
array_buffer_transfer_map_.Insert(array_buffer, transfer_id);
}
Maybe<bool> ValueSerializer::WriteObject(Handle<Object> object) {
// There is no sense in trying to proceed if we've previously run out of
// memory. Bail immediately, as this likely implies that some write has
// previously failed and so the buffer is corrupt.
if (V8_UNLIKELY(out_of_memory_)) return ThrowIfOutOfMemory();
if (object->IsSmi()) {
WriteSmi(Smi::cast(*object));
return ThrowIfOutOfMemory();
}
DCHECK(object->IsHeapObject());
InstanceType instance_type =
HeapObject::cast(*object).map(isolate_).instance_type();
switch (instance_type) {
case ODDBALL_TYPE:
WriteOddball(Oddball::cast(*object));
return ThrowIfOutOfMemory();
case HEAP_NUMBER_TYPE:
WriteHeapNumber(HeapNumber::cast(*object));
return ThrowIfOutOfMemory();
case BIGINT_TYPE:
WriteBigInt(BigInt::cast(*object));
return ThrowIfOutOfMemory();
case JS_TYPED_ARRAY_TYPE:
case JS_DATA_VIEW_TYPE: {
// Despite being JSReceivers, these have their wrapped buffer serialized
// first. That makes this logic a little quirky, because it needs to
// happen before we assign object IDs.
// TODO(jbroman): It may be possible to avoid materializing a typed
// array's buffer here.
Handle<JSArrayBufferView> view = Handle<JSArrayBufferView>::cast(object);
if (!id_map_.Find(view) && !treat_array_buffer_views_as_host_objects_) {
Handle<JSArrayBuffer> buffer(
InstanceTypeChecker::IsJSTypedArray(instance_type)
? Handle<JSTypedArray>::cast(view)->GetBuffer()
: handle(JSArrayBuffer::cast(view->buffer()), isolate_));
if (!WriteJSReceiver(buffer).FromMaybe(false)) return Nothing<bool>();
}
return WriteJSReceiver(view);
}
default:
if (InstanceTypeChecker::IsString(instance_type)) {
auto string = Handle<String>::cast(object);
if (FLAG_shared_string_table && supports_shared_values_) {
return WriteSharedObject(String::Share(isolate_, string));
}
WriteString(string);
return ThrowIfOutOfMemory();
} else if (InstanceTypeChecker::IsJSReceiver(instance_type)) {
return WriteJSReceiver(Handle<JSReceiver>::cast(object));
} else {
return ThrowDataCloneError(MessageTemplate::kDataCloneError, object);
}
}
}
void ValueSerializer::WriteOddball(Oddball oddball) {
SerializationTag tag = SerializationTag::kUndefined;
switch (oddball.kind()) {
case Oddball::kUndefined:
tag = SerializationTag::kUndefined;
break;
case Oddball::kFalse:
tag = SerializationTag::kFalse;
break;
case Oddball::kTrue:
tag = SerializationTag::kTrue;
break;
case Oddball::kNull:
tag = SerializationTag::kNull;
break;
default:
UNREACHABLE();
}
WriteTag(tag);
}
void ValueSerializer::WriteSmi(Smi smi) {
static_assert(kSmiValueSize <= 32, "Expected SMI <= 32 bits.");
WriteTag(SerializationTag::kInt32);
WriteZigZag<int32_t>(smi.value());
}
void ValueSerializer::WriteHeapNumber(HeapNumber number) {
WriteTag(SerializationTag::kDouble);
WriteDouble(number.value());
}
void ValueSerializer::WriteBigInt(BigInt bigint) {
WriteTag(SerializationTag::kBigInt);
WriteBigIntContents(bigint);
}
void ValueSerializer::WriteString(Handle<String> string) {
string = String::Flatten(isolate_, string);
DisallowGarbageCollection no_gc;
String::FlatContent flat = string->GetFlatContent(no_gc);
DCHECK(flat.IsFlat());
if (flat.IsOneByte()) {
base::Vector<const uint8_t> chars = flat.ToOneByteVector();
WriteTag(SerializationTag::kOneByteString);
WriteOneByteString(chars);
} else if (flat.IsTwoByte()) {
base::Vector<const base::uc16> chars = flat.ToUC16Vector();
uint32_t byte_length = chars.length() * sizeof(base::uc16);
// The existing reading code expects 16-byte strings to be aligned.
if ((buffer_size_ + 1 + BytesNeededForVarint(byte_length)) & 1)
WriteTag(SerializationTag::kPadding);
WriteTag(SerializationTag::kTwoByteString);
WriteTwoByteString(chars);
} else {
UNREACHABLE();
}
}
Maybe<bool> ValueSerializer::WriteJSReceiver(Handle<JSReceiver> receiver) {
// If the object has already been serialized, just write its ID.
auto find_result = id_map_.FindOrInsert(receiver);
if (find_result.already_exists) {
WriteTag(SerializationTag::kObjectReference);
WriteVarint(*find_result.entry - 1);
return ThrowIfOutOfMemory();
}
// Otherwise, allocate an ID for it.
uint32_t id = next_id_++;
*find_result.entry = id + 1;
// Eliminate callable and exotic objects, which should not be serialized.
InstanceType instance_type = receiver->map().instance_type();
if (receiver->IsCallable() || (IsSpecialReceiverInstanceType(instance_type) &&
instance_type != JS_SPECIAL_API_OBJECT_TYPE)) {
return ThrowDataCloneError(MessageTemplate::kDataCloneError, receiver);
}
// If we are at the end of the stack, abort. This function may recurse.
STACK_CHECK(isolate_, Nothing<bool>());
HandleScope scope(isolate_);
switch (instance_type) {
case JS_ARRAY_TYPE:
return WriteJSArray(Handle<JSArray>::cast(receiver));
case JS_ARRAY_ITERATOR_PROTOTYPE_TYPE:
case JS_ITERATOR_PROTOTYPE_TYPE:
case JS_MAP_ITERATOR_PROTOTYPE_TYPE:
case JS_OBJECT_PROTOTYPE_TYPE:
case JS_OBJECT_TYPE:
case JS_PROMISE_PROTOTYPE_TYPE:
case JS_REG_EXP_PROTOTYPE_TYPE:
case JS_SET_ITERATOR_PROTOTYPE_TYPE:
case JS_SET_PROTOTYPE_TYPE:
case JS_STRING_ITERATOR_PROTOTYPE_TYPE:
case JS_TYPED_ARRAY_PROTOTYPE_TYPE:
case JS_API_OBJECT_TYPE: {
Handle<JSObject> js_object = Handle<JSObject>::cast(receiver);
if (JSObject::GetEmbedderFieldCount(js_object->map(isolate_))) {
return WriteHostObject(js_object);
} else {
return WriteJSObject(js_object);
}
}
case JS_SPECIAL_API_OBJECT_TYPE:
return WriteHostObject(Handle<JSObject>::cast(receiver));
case JS_DATE_TYPE:
WriteJSDate(JSDate::cast(*receiver));
return ThrowIfOutOfMemory();
case JS_PRIMITIVE_WRAPPER_TYPE:
return WriteJSPrimitiveWrapper(
Handle<JSPrimitiveWrapper>::cast(receiver));
case JS_REG_EXP_TYPE:
WriteJSRegExp(Handle<JSRegExp>::cast(receiver));
return ThrowIfOutOfMemory();
case JS_MAP_TYPE:
return WriteJSMap(Handle<JSMap>::cast(receiver));
case JS_SET_TYPE:
return WriteJSSet(Handle<JSSet>::cast(receiver));
case JS_ARRAY_BUFFER_TYPE:
return WriteJSArrayBuffer(Handle<JSArrayBuffer>::cast(receiver));
case JS_TYPED_ARRAY_TYPE:
case JS_DATA_VIEW_TYPE:
return WriteJSArrayBufferView(JSArrayBufferView::cast(*receiver));
case JS_ERROR_TYPE:
return WriteJSError(Handle<JSObject>::cast(receiver));
case JS_SHARED_STRUCT_TYPE:
return WriteJSSharedStruct(Handle<JSSharedStruct>::cast(receiver));
#if V8_ENABLE_WEBASSEMBLY
case WASM_MODULE_OBJECT_TYPE:
return WriteWasmModule(Handle<WasmModuleObject>::cast(receiver));
case WASM_MEMORY_OBJECT_TYPE: {
auto enabled_features = wasm::WasmFeatures::FromIsolate(isolate_);
if (enabled_features.has_threads()) {
return WriteWasmMemory(Handle<WasmMemoryObject>::cast(receiver));
}
break;
}
#endif // V8_ENABLE_WEBASSEMBLY
default:
break;
}
return ThrowDataCloneError(MessageTemplate::kDataCloneError, receiver);
}
Maybe<bool> ValueSerializer::WriteJSObject(Handle<JSObject> object) {
DCHECK(!object->map().IsCustomElementsReceiverMap());
const bool can_serialize_fast =
object->HasFastProperties(isolate_) && object->elements().length() == 0;
if (!can_serialize_fast) return WriteJSObjectSlow(object);
Handle<Map> map(object->map(), isolate_);
WriteTag(SerializationTag::kBeginJSObject);
// Write out fast properties as long as they are only data properties and the
// map doesn't change.
uint32_t properties_written = 0;
bool map_changed = false;
for (InternalIndex i : map->IterateOwnDescriptors()) {
Handle<Name> key(map->instance_descriptors(isolate_).GetKey(i), isolate_);
if (!key->IsString(isolate_)) continue;
PropertyDetails details = map->instance_descriptors(isolate_).GetDetails(i);
if (details.IsDontEnum()) continue;
Handle<Object> value;
if (V8_LIKELY(!map_changed)) map_changed = *map != object->map();
if (V8_LIKELY(!map_changed &&
details.location() == PropertyLocation::kField)) {
DCHECK_EQ(PropertyKind::kData, details.kind());
FieldIndex field_index = FieldIndex::ForDescriptor(*map, i);
value = JSObject::FastPropertyAt(isolate_, object,
details.representation(), field_index);
} else {
// This logic should essentially match WriteJSObjectPropertiesSlow.
// If the property is no longer found, do not serialize it.
// This could happen if a getter deleted the property.
LookupIterator it(isolate_, object, key, LookupIterator::OWN);
if (!it.IsFound()) continue;
if (!Object::GetProperty(&it).ToHandle(&value)) return Nothing<bool>();
}
if (!WriteObject(key).FromMaybe(false) ||
!WriteObject(value).FromMaybe(false)) {
return Nothing<bool>();
}
properties_written++;
}
WriteTag(SerializationTag::kEndJSObject);
WriteVarint<uint32_t>(properties_written);
return ThrowIfOutOfMemory();
}
Maybe<bool> ValueSerializer::WriteJSObjectSlow(Handle<JSObject> object) {
WriteTag(SerializationTag::kBeginJSObject);
Handle<FixedArray> keys;
uint32_t properties_written = 0;
if (!KeyAccumulator::GetKeys(object, KeyCollectionMode::kOwnOnly,
ENUMERABLE_STRINGS)
.ToHandle(&keys) ||
!WriteJSObjectPropertiesSlow(object, keys).To(&properties_written)) {
return Nothing<bool>();
}
WriteTag(SerializationTag::kEndJSObject);
WriteVarint<uint32_t>(properties_written);
return ThrowIfOutOfMemory();
}
Maybe<bool> ValueSerializer::WriteJSArray(Handle<JSArray> array) {
PtrComprCageBase cage_base(isolate_);
uint32_t length = 0;
bool valid_length = array->length().ToArrayLength(&length);
DCHECK(valid_length);
USE(valid_length);
// To keep things simple, for now we decide between dense and sparse
// serialization based on elements kind. A more principled heuristic could
// count the elements, but would need to take care to note which indices
// existed (as only indices which were enumerable own properties at this point
// should be serialized).
const bool should_serialize_densely =
array->HasFastElements(cage_base) && !array->HasHoleyElements(cage_base);
if (should_serialize_densely) {
DCHECK_LE(length, static_cast<uint32_t>(FixedArray::kMaxLength));
WriteTag(SerializationTag::kBeginDenseJSArray);
WriteVarint<uint32_t>(length);
uint32_t i = 0;
// Fast paths. Note that PACKED_ELEMENTS in particular can bail due to the
// structure of the elements changing.
switch (array->GetElementsKind(cage_base)) {
case PACKED_SMI_ELEMENTS: {
DisallowGarbageCollection no_gc;
FixedArray elements = FixedArray::cast(array->elements());
for (i = 0; i < length; i++)
WriteSmi(Smi::cast(elements.get(cage_base, i)));
break;
}
case PACKED_DOUBLE_ELEMENTS: {
// Elements are empty_fixed_array, not a FixedDoubleArray, if the array
// is empty. No elements to encode in this case anyhow.
if (length == 0) break;
DisallowGarbageCollection no_gc;
FixedDoubleArray elements = FixedDoubleArray::cast(array->elements());
for (i = 0; i < length; i++) {
WriteTag(SerializationTag::kDouble);
WriteDouble(elements.get_scalar(i));
}
break;
}
case PACKED_ELEMENTS: {
Handle<Object> old_length(array->length(cage_base), isolate_);
for (; i < length; i++) {
if (array->length(cage_base) != *old_length ||
array->GetElementsKind(cage_base) != PACKED_ELEMENTS) {
// Fall back to slow path.
break;
}
Handle<Object> element(
FixedArray::cast(array->elements()).get(cage_base, i), isolate_);
if (!WriteObject(element).FromMaybe(false)) return Nothing<bool>();
}
break;
}
default:
break;
}
// If there are elements remaining, serialize them slowly.
for (; i < length; i++) {
// Serializing the array's elements can have arbitrary side effects, so we
// cannot rely on still having fast elements, even if it did to begin
// with.
Handle<Object> element;
LookupIterator it(isolate_, array, i, array, LookupIterator::OWN);
if (!it.IsFound()) {
// This can happen in the case where an array that was originally dense
// became sparse during serialization. It's too late to switch to the
// sparse format, but we can mark the elements as absent.
WriteTag(SerializationTag::kTheHole);
continue;
}
if (!Object::GetProperty(&it).ToHandle(&element) ||
!WriteObject(element).FromMaybe(false)) {
return Nothing<bool>();
}
}
Handle<FixedArray> keys;
if (!KeyAccumulator::GetKeys(array, KeyCollectionMode::kOwnOnly,
ENUMERABLE_STRINGS,
GetKeysConversion::kKeepNumbers, false, true)
.ToHandle(&keys)) {
return Nothing<bool>();
}
uint32_t properties_written;
if (!WriteJSObjectPropertiesSlow(array, keys).To(&properties_written)) {
return Nothing<bool>();
}
WriteTag(SerializationTag::kEndDenseJSArray);
WriteVarint<uint32_t>(properties_written);
WriteVarint<uint32_t>(length);
} else {
WriteTag(SerializationTag::kBeginSparseJSArray);
WriteVarint<uint32_t>(length);
Handle<FixedArray> keys;
uint32_t properties_written = 0;
if (!KeyAccumulator::GetKeys(array, KeyCollectionMode::kOwnOnly,
ENUMERABLE_STRINGS)
.ToHandle(&keys) ||
!WriteJSObjectPropertiesSlow(array, keys).To(&properties_written)) {
return Nothing<bool>();
}
WriteTag(SerializationTag::kEndSparseJSArray);
WriteVarint<uint32_t>(properties_written);
WriteVarint<uint32_t>(length);
}
return ThrowIfOutOfMemory();
}
void ValueSerializer::WriteJSDate(JSDate date) {
WriteTag(SerializationTag::kDate);
WriteDouble(date.value().Number());
}
Maybe<bool> ValueSerializer::WriteJSPrimitiveWrapper(
Handle<JSPrimitiveWrapper> value) {
PtrComprCageBase cage_base(isolate_);
{
DisallowGarbageCollection no_gc;
Object inner_value = value->value();
if (inner_value.IsTrue(isolate_)) {
WriteTag(SerializationTag::kTrueObject);
} else if (inner_value.IsFalse(isolate_)) {
WriteTag(SerializationTag::kFalseObject);
} else if (inner_value.IsNumber(cage_base)) {
WriteTag(SerializationTag::kNumberObject);
WriteDouble(inner_value.Number());
} else if (inner_value.IsBigInt(cage_base)) {
WriteTag(SerializationTag::kBigIntObject);
WriteBigIntContents(BigInt::cast(inner_value));
} else if (inner_value.IsString(cage_base)) {
WriteTag(SerializationTag::kStringObject);
WriteString(handle(String::cast(inner_value), isolate_));
} else {
AllowGarbageCollection allow_gc;
DCHECK(inner_value.IsSymbol());
return ThrowDataCloneError(MessageTemplate::kDataCloneError, value);
}
}
return ThrowIfOutOfMemory();
}
void ValueSerializer::WriteJSRegExp(Handle<JSRegExp> regexp) {
WriteTag(SerializationTag::kRegExp);
WriteString(handle(regexp->source(), isolate_));
WriteVarint(static_cast<uint32_t>(regexp->flags()));
}
Maybe<bool> ValueSerializer::WriteJSMap(Handle<JSMap> js_map) {
// First copy the key-value pairs, since getters could mutate them.
Handle<OrderedHashMap> table(OrderedHashMap::cast(js_map->table()), isolate_);
int length = table->NumberOfElements() * 2;
Handle<FixedArray> entries = isolate_->factory()->NewFixedArray(length);
{
DisallowGarbageCollection no_gc;
OrderedHashMap raw_table = *table;
FixedArray raw_entries = *entries;
Oddball the_hole = ReadOnlyRoots(isolate_).the_hole_value();
int result_index = 0;
for (InternalIndex entry : raw_table.IterateEntries()) {
Object key = raw_table.KeyAt(entry);
if (key == the_hole) continue;
raw_entries.set(result_index++, key);
raw_entries.set(result_index++, raw_table.ValueAt(entry));
}
DCHECK_EQ(result_index, length);
}
// Then write it out.
WriteTag(SerializationTag::kBeginJSMap);
for (int i = 0; i < length; i++) {
if (!WriteObject(handle(entries->get(i), isolate_)).FromMaybe(false)) {
return Nothing<bool>();
}
}
WriteTag(SerializationTag::kEndJSMap);
WriteVarint<uint32_t>(length);
return ThrowIfOutOfMemory();
}
Maybe<bool> ValueSerializer::WriteJSSet(Handle<JSSet> js_set) {
// First copy the element pointers, since getters could mutate them.
Handle<OrderedHashSet> table(OrderedHashSet::cast(js_set->table()), isolate_);
int length = table->NumberOfElements();
Handle<FixedArray> entries = isolate_->factory()->NewFixedArray(length);
{
DisallowGarbageCollection no_gc;
OrderedHashSet raw_table = *table;
FixedArray raw_entries = *entries;
Oddball the_hole = ReadOnlyRoots(isolate_).the_hole_value();
int result_index = 0;
for (InternalIndex entry : raw_table.IterateEntries()) {
Object key = raw_table.KeyAt(entry);
if (key == the_hole) continue;
raw_entries.set(result_index++, key);
}
DCHECK_EQ(result_index, length);
}
// Then write it out.
WriteTag(SerializationTag::kBeginJSSet);
for (int i = 0; i < length; i++) {
if (!WriteObject(handle(entries->get(i), isolate_)).FromMaybe(false)) {
return Nothing<bool>();
}
}
WriteTag(SerializationTag::kEndJSSet);
WriteVarint<uint32_t>(length);
return ThrowIfOutOfMemory();
}
Maybe<bool> ValueSerializer::WriteJSArrayBuffer(
Handle<JSArrayBuffer> array_buffer) {
if (array_buffer->is_shared()) {
if (!delegate_) {
return ThrowDataCloneError(MessageTemplate::kDataCloneError,
array_buffer);
}
v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate_);
Maybe<uint32_t> index = delegate_->GetSharedArrayBufferId(
v8_isolate, Utils::ToLocalShared(array_buffer));
RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate_, Nothing<bool>());
WriteTag(SerializationTag::kSharedArrayBuffer);
WriteVarint(index.FromJust());
return ThrowIfOutOfMemory();
}
uint32_t* transfer_entry = array_buffer_transfer_map_.Find(array_buffer);
if (transfer_entry) {
WriteTag(SerializationTag::kArrayBufferTransfer);
WriteVarint(*transfer_entry);
return ThrowIfOutOfMemory();
}
if (array_buffer->was_detached()) {
return ThrowDataCloneError(
MessageTemplate::kDataCloneErrorDetachedArrayBuffer);
}
double byte_length = array_buffer->byte_length();
if (byte_length > std::numeric_limits<uint32_t>::max()) {
return ThrowDataCloneError(MessageTemplate::kDataCloneError, array_buffer);
}
// TODO(v8:11111): Support RAB / GSAB. The wire version will need to be
// bumped.
WriteTag(SerializationTag::kArrayBuffer);
WriteVarint<uint32_t>(byte_length);
WriteRawBytes(array_buffer->backing_store(), byte_length);
return ThrowIfOutOfMemory();
}
Maybe<bool> ValueSerializer::WriteJSArrayBufferView(JSArrayBufferView view) {
if (treat_array_buffer_views_as_host_objects_) {
return WriteHostObject(handle(view, isolate_));
}
WriteTag(SerializationTag::kArrayBufferView);
ArrayBufferViewTag tag = ArrayBufferViewTag::kInt8Array;
if (view.IsJSTypedArray()) {
switch (JSTypedArray::cast(view).type()) {
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype) \
case kExternal##Type##Array: \
tag = ArrayBufferViewTag::k##Type##Array; \
break;
TYPED_ARRAYS(TYPED_ARRAY_CASE)
#undef TYPED_ARRAY_CASE
}
} else {
DCHECK(view.IsJSDataView());
tag = ArrayBufferViewTag::kDataView;
}
WriteVarint(static_cast<uint8_t>(tag));
WriteVarint(static_cast<uint32_t>(view.byte_offset()));
WriteVarint(static_cast<uint32_t>(view.byte_length()));
uint32_t flags =
JSArrayBufferViewIsLengthTracking::encode(view.is_length_tracking()) |
JSArrayBufferViewIsBackedByRab::encode(view.is_backed_by_rab());
WriteVarint(flags);
return ThrowIfOutOfMemory();
}
Maybe<bool> ValueSerializer::WriteJSError(Handle<JSObject> error) {
Handle<Object> stack;
PropertyDescriptor message_desc;
Maybe<bool> message_found = JSReceiver::GetOwnPropertyDescriptor(
isolate_, error, isolate_->factory()->message_string(), &message_desc);
MAYBE_RETURN(message_found, Nothing<bool>());
PropertyDescriptor cause_desc;
Maybe<bool> cause_found = JSReceiver::GetOwnPropertyDescriptor(
isolate_, error, isolate_->factory()->cause_string(), &cause_desc);
WriteTag(SerializationTag::kError);
Handle<Object> name_object;
if (!JSObject::GetProperty(isolate_, error, "name").ToHandle(&name_object)) {
return Nothing<bool>();
}
Handle<String> name;
if (!Object::ToString(isolate_, name_object).ToHandle(&name)) {
return Nothing<bool>();
}
if (name->IsOneByteEqualTo(base::CStrVector("EvalError"))) {
WriteVarint(static_cast<uint8_t>(ErrorTag::kEvalErrorPrototype));
} else if (name->IsOneByteEqualTo(base::CStrVector("RangeError"))) {
WriteVarint(static_cast<uint8_t>(ErrorTag::kRangeErrorPrototype));
} else if (name->IsOneByteEqualTo(base::CStrVector("ReferenceError"))) {
WriteVarint(static_cast<uint8_t>(ErrorTag::kReferenceErrorPrototype));
} else if (name->IsOneByteEqualTo(base::CStrVector("SyntaxError"))) {