forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
value-serializer-unittest.cc
3548 lines (3145 loc) · 137 KB
/
value-serializer-unittest.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 <algorithm>
#include <string>
#include "include/v8-context.h"
#include "include/v8-date.h"
#include "include/v8-function.h"
#include "include/v8-json.h"
#include "include/v8-local-handle.h"
#include "include/v8-primitive-object.h"
#include "include/v8-template.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/build_config.h"
#include "src/objects/backing-store.h"
#include "src/objects/js-array-buffer-inl.h"
#include "src/objects/js-array-buffer.h"
#include "src/objects/objects-inl.h"
#include "test/common/flag-utils.h"
#include "test/unittests/test-utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#if V8_ENABLE_WEBASSEMBLY
#include "src/wasm/wasm-engine.h"
#include "src/wasm/wasm-objects.h"
#include "src/wasm/wasm-result.h"
#endif // V8_ENABLE_WEBASSEMBLY
namespace v8 {
namespace {
using ::testing::_;
using ::testing::Invoke;
using ::testing::Return;
class ValueSerializerTest : public TestWithIsolate {
public:
ValueSerializerTest(const ValueSerializerTest&) = delete;
ValueSerializerTest& operator=(const ValueSerializerTest&) = delete;
protected:
ValueSerializerTest()
: serialization_context_(Context::New(isolate())),
deserialization_context_(Context::New(isolate())) {
// Create a host object type that can be tested through
// serialization/deserialization delegates below.
Local<FunctionTemplate> function_template = v8::FunctionTemplate::New(
isolate(), [](const FunctionCallbackInfo<Value>& args) {
args.Holder()->SetInternalField(0, args[0]);
args.Holder()->SetInternalField(1, args[1]);
});
function_template->InstanceTemplate()->SetInternalFieldCount(2);
function_template->InstanceTemplate()->SetAccessor(
StringFromUtf8("value"),
[](Local<String> property, const PropertyCallbackInfo<Value>& args) {
args.GetReturnValue().Set(args.Holder()->GetInternalField(0));
});
function_template->InstanceTemplate()->SetAccessor(
StringFromUtf8("value2"),
[](Local<String> property, const PropertyCallbackInfo<Value>& args) {
args.GetReturnValue().Set(args.Holder()->GetInternalField(1));
});
for (Local<Context> context :
{serialization_context_, deserialization_context_}) {
context->Global()
->CreateDataProperty(
context, StringFromUtf8("ExampleHostObject"),
function_template->GetFunction(context).ToLocalChecked())
.ToChecked();
}
host_object_constructor_template_ = function_template;
isolate_ = reinterpret_cast<i::Isolate*>(isolate());
}
~ValueSerializerTest() override {
// In some cases unhandled scheduled exceptions from current test produce
// that Context::New(isolate()) from next test's constructor returns NULL.
// In order to prevent that, we added destructor which will clear scheduled
// exceptions just for the current test from test case.
if (isolate_->has_scheduled_exception()) {
isolate_->clear_scheduled_exception();
}
}
const Local<Context>& serialization_context() {
return serialization_context_;
}
const Local<Context>& deserialization_context() {
return deserialization_context_;
}
// Overridden in more specific fixtures.
virtual ValueSerializer::Delegate* GetSerializerDelegate() { return nullptr; }
virtual void BeforeEncode(ValueSerializer*) {}
virtual ValueDeserializer::Delegate* GetDeserializerDelegate() {
return nullptr;
}
virtual void BeforeDecode(ValueDeserializer*) {}
Local<Value> RoundTripTest(Local<Value> input_value) {
std::vector<uint8_t> encoded = EncodeTest(input_value);
return DecodeTest(encoded);
}
// Variant for the common case where a script is used to build the original
// value.
Local<Value> RoundTripTest(const char* source) {
return RoundTripTest(EvaluateScriptForInput(source));
}
// Variant which uses JSON.parse/stringify to check the result.
void RoundTripJSON(const char* source) {
Local<Value> input_value =
JSON::Parse(serialization_context_, StringFromUtf8(source))
.ToLocalChecked();
Local<Value> result = RoundTripTest(input_value);
ASSERT_TRUE(result->IsObject());
EXPECT_EQ(source, Utf8Value(JSON::Stringify(deserialization_context_,
result.As<Object>())
.ToLocalChecked()));
}
Maybe<std::vector<uint8_t>> DoEncode(Local<Value> value) {
Local<Context> context = serialization_context();
ValueSerializer serializer(isolate(), GetSerializerDelegate());
BeforeEncode(&serializer);
serializer.WriteHeader();
if (!serializer.WriteValue(context, value).FromMaybe(false)) {
return Nothing<std::vector<uint8_t>>();
}
std::pair<uint8_t*, size_t> buffer = serializer.Release();
std::vector<uint8_t> result(buffer.first, buffer.first + buffer.second);
if (auto* delegate = GetSerializerDelegate())
delegate->FreeBufferMemory(buffer.first);
else
free(buffer.first);
return Just(std::move(result));
}
std::vector<uint8_t> EncodeTest(Local<Value> input_value) {
Context::Scope scope(serialization_context());
TryCatch try_catch(isolate());
std::vector<uint8_t> buffer;
// Ideally we would use GTest's ASSERT_* macros here and below. However,
// those only work in functions returning {void}, and they only terminate
// the current function, but not the entire current test (so we would need
// additional manual checks whether it is okay to proceed). Given that our
// test driver starts a new process for each test anyway, it is acceptable
// to just use a CHECK (which would kill the process on failure) instead.
CHECK(DoEncode(input_value).To(&buffer));
CHECK(!try_catch.HasCaught());
return buffer;
}
std::vector<uint8_t> EncodeTest(const char* source) {
return EncodeTest(EvaluateScriptForInput(source));
}
v8::Local<v8::Message> InvalidEncodeTest(Local<Value> input_value) {
Context::Scope scope(serialization_context());
TryCatch try_catch(isolate());
CHECK(DoEncode(input_value).IsNothing());
return try_catch.Message();
}
v8::Local<v8::Message> InvalidEncodeTest(const char* source) {
return InvalidEncodeTest(EvaluateScriptForInput(source));
}
Local<Value> DecodeTest(const std::vector<uint8_t>& data) {
Local<Context> context = deserialization_context();
Context::Scope scope(context);
TryCatch try_catch(isolate());
ValueDeserializer deserializer(isolate(), &data[0],
static_cast<int>(data.size()),
GetDeserializerDelegate());
deserializer.SetSupportsLegacyWireFormat(true);
BeforeDecode(&deserializer);
CHECK(deserializer.ReadHeader(context).FromMaybe(false));
Local<Value> result;
CHECK(deserializer.ReadValue(context).ToLocal(&result));
CHECK(!result.IsEmpty());
CHECK(!try_catch.HasCaught());
CHECK(context->Global()
->CreateDataProperty(context, StringFromUtf8("result"), result)
.FromMaybe(false));
CHECK(!try_catch.HasCaught());
return result;
}
template <typename Lambda>
void DecodeTestFutureVersions(std::vector<uint8_t>&& data, Lambda test) {
DecodeTestUpToVersion(v8::CurrentValueSerializerFormatVersion(),
std::move(data), test);
}
template <typename Lambda>
void DecodeTestUpToVersion(int last_version, std::vector<uint8_t>&& data,
Lambda test) {
// Check that there is at least one version to test.
CHECK_LE(data[1], last_version);
for (int version = data[1]; version <= last_version; ++version) {
data[1] = version;
Local<Value> value = DecodeTest(data);
test(value);
}
}
Local<Value> DecodeTestForVersion0(const std::vector<uint8_t>& data) {
Local<Context> context = deserialization_context();
Context::Scope scope(context);
TryCatch try_catch(isolate());
ValueDeserializer deserializer(isolate(), &data[0],
static_cast<int>(data.size()),
GetDeserializerDelegate());
deserializer.SetSupportsLegacyWireFormat(true);
BeforeDecode(&deserializer);
CHECK(deserializer.ReadHeader(context).FromMaybe(false));
CHECK_EQ(0u, deserializer.GetWireFormatVersion());
Local<Value> result;
CHECK(deserializer.ReadValue(context).ToLocal(&result));
CHECK(!result.IsEmpty());
CHECK(!try_catch.HasCaught());
CHECK(context->Global()
->CreateDataProperty(context, StringFromUtf8("result"), result)
.FromMaybe(false));
CHECK(!try_catch.HasCaught());
return result;
}
void InvalidDecodeTest(const std::vector<uint8_t>& data) {
Local<Context> context = deserialization_context();
Context::Scope scope(context);
TryCatch try_catch(isolate());
ValueDeserializer deserializer(isolate(), &data[0],
static_cast<int>(data.size()),
GetDeserializerDelegate());
deserializer.SetSupportsLegacyWireFormat(true);
BeforeDecode(&deserializer);
Maybe<bool> header_result = deserializer.ReadHeader(context);
if (header_result.IsNothing()) {
EXPECT_TRUE(try_catch.HasCaught());
return;
}
CHECK(header_result.ToChecked());
CHECK(deserializer.ReadValue(context).IsEmpty());
EXPECT_TRUE(try_catch.HasCaught());
}
Local<Value> EvaluateScriptForInput(const char* utf8_source) {
Context::Scope scope(serialization_context_);
Local<String> source = StringFromUtf8(utf8_source);
Local<Script> script =
Script::Compile(serialization_context_, source).ToLocalChecked();
return script->Run(serialization_context_).ToLocalChecked();
}
void ExpectScriptTrue(const char* utf8_source) {
Context::Scope scope(deserialization_context_);
Local<String> source = StringFromUtf8(utf8_source);
Local<Script> script =
Script::Compile(deserialization_context_, source).ToLocalChecked();
Local<Value> value = script->Run(deserialization_context_).ToLocalChecked();
EXPECT_TRUE(value->BooleanValue(isolate()));
}
Local<String> StringFromUtf8(const char* source) {
return String::NewFromUtf8(isolate(), source).ToLocalChecked();
}
std::string Utf8Value(Local<Value> value) {
String::Utf8Value utf8(isolate(), value);
return std::string(*utf8, utf8.length());
}
Local<Object> NewHostObject(Local<Context> context, int argc,
Local<Value> argv[]) {
return host_object_constructor_template_->GetFunction(context)
.ToLocalChecked()
->NewInstance(context, argc, argv)
.ToLocalChecked();
}
Local<Object> NewDummyUint8Array() {
const uint8_t data[] = {4, 5, 6};
Local<ArrayBuffer> ab = ArrayBuffer::New(isolate(), sizeof(data));
memcpy(ab->GetBackingStore()->Data(), data, sizeof(data));
return Uint8Array::New(ab, 0, sizeof(data));
}
private:
Local<Context> serialization_context_;
Local<Context> deserialization_context_;
Local<FunctionTemplate> host_object_constructor_template_;
i::Isolate* isolate_;
};
TEST_F(ValueSerializerTest, DecodeInvalid) {
// Version tag but no content.
InvalidDecodeTest({0xFF});
// Version too large.
InvalidDecodeTest({0xFF, 0x7F, 0x5F});
// Nonsense tag.
InvalidDecodeTest({0xFF, 0x09, 0xDD});
}
TEST_F(ValueSerializerTest, RoundTripOddball) {
Local<Value> value = RoundTripTest(Undefined(isolate()));
EXPECT_TRUE(value->IsUndefined());
value = RoundTripTest(True(isolate()));
EXPECT_TRUE(value->IsTrue());
value = RoundTripTest(False(isolate()));
EXPECT_TRUE(value->IsFalse());
value = RoundTripTest(Null(isolate()));
EXPECT_TRUE(value->IsNull());
}
TEST_F(ValueSerializerTest, DecodeOddball) {
// What this code is expected to generate.
DecodeTestFutureVersions({0xFF, 0x09, 0x5F}, [](Local<Value> value) {
EXPECT_TRUE(value->IsUndefined());
});
DecodeTestFutureVersions({0xFF, 0x09, 0x54}, [](Local<Value> value) {
EXPECT_TRUE(value->IsTrue());
});
DecodeTestFutureVersions({0xFF, 0x09, 0x46}, [](Local<Value> value) {
EXPECT_TRUE(value->IsFalse());
});
DecodeTestFutureVersions({0xFF, 0x09, 0x30}, [](Local<Value> value) {
EXPECT_TRUE(value->IsNull());
});
// What v9 of the Blink code generates.
Local<Value> value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x5F, 0x00});
EXPECT_TRUE(value->IsUndefined());
value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x54, 0x00});
EXPECT_TRUE(value->IsTrue());
value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x46, 0x00});
EXPECT_TRUE(value->IsFalse());
value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x30, 0x00});
EXPECT_TRUE(value->IsNull());
// v0 (with no explicit version).
value = DecodeTest({0x5F, 0x00});
EXPECT_TRUE(value->IsUndefined());
value = DecodeTest({0x54, 0x00});
EXPECT_TRUE(value->IsTrue());
value = DecodeTest({0x46, 0x00});
EXPECT_TRUE(value->IsFalse());
value = DecodeTest({0x30, 0x00});
EXPECT_TRUE(value->IsNull());
}
TEST_F(ValueSerializerTest, EncodeArrayStackOverflow) {
InvalidEncodeTest("var a = []; for (var i = 0; i < 1E5; i++) a = [a]; a");
}
TEST_F(ValueSerializerTest, EncodeObjectStackOverflow) {
InvalidEncodeTest("var a = {}; for (var i = 0; i < 1E5; i++) a = {a}; a");
}
TEST_F(ValueSerializerTest, DecodeArrayStackOverflow) {
static const int nesting_level = 1E5;
std::vector<uint8_t> payload;
// Header.
payload.push_back(0xFF);
payload.push_back(0x0D);
// Nested arrays, each with one element.
for (int i = 0; i < nesting_level; i++) {
payload.push_back(0x41);
payload.push_back(0x01);
}
// Innermost array is empty.
payload.push_back(0x41);
payload.push_back(0x00);
payload.push_back(0x24);
payload.push_back(0x00);
payload.push_back(0x00);
// Close nesting.
for (int i = 0; i < nesting_level; i++) {
payload.push_back(0x24);
payload.push_back(0x00);
payload.push_back(0x01);
}
InvalidDecodeTest(payload);
}
TEST_F(ValueSerializerTest, DecodeObjectStackOverflow) {
static const int nesting_level = 1E5;
std::vector<uint8_t> payload;
// Header.
payload.push_back(0xFF);
payload.push_back(0x0D);
// Nested objects, each with one property 'a'.
for (int i = 0; i < nesting_level; i++) {
payload.push_back(0x6F);
payload.push_back(0x22);
payload.push_back(0x01);
payload.push_back(0x61);
}
// Innermost array is empty.
payload.push_back(0x6F);
payload.push_back(0x7B);
payload.push_back(0x00);
// Close nesting.
for (int i = 0; i < nesting_level; i++) {
payload.push_back(0x7B);
payload.push_back(0x01);
}
InvalidDecodeTest(payload);
}
TEST_F(ValueSerializerTest, DecodeVerifyObjectCount) {
static const int nesting_level = 1E5;
std::vector<uint8_t> payload;
// Header.
payload.push_back(0xFF);
payload.push_back(0x0D);
// Repeat SerializationTag:kVerifyObjectCount. This leads to stack overflow.
for (int i = 0; i < nesting_level; i++) {
payload.push_back(0x3F);
payload.push_back(0x01);
}
InvalidDecodeTest(payload);
}
TEST_F(ValueSerializerTest, RoundTripNumber) {
Local<Value> value = RoundTripTest(Integer::New(isolate(), 42));
ASSERT_TRUE(value->IsInt32());
EXPECT_EQ(42, Int32::Cast(*value)->Value());
value = RoundTripTest(Integer::New(isolate(), -31337));
ASSERT_TRUE(value->IsInt32());
EXPECT_EQ(-31337, Int32::Cast(*value)->Value());
value = RoundTripTest(
Integer::New(isolate(), std::numeric_limits<int32_t>::min()));
ASSERT_TRUE(value->IsInt32());
EXPECT_EQ(std::numeric_limits<int32_t>::min(), Int32::Cast(*value)->Value());
value = RoundTripTest(Number::New(isolate(), -0.25));
ASSERT_TRUE(value->IsNumber());
EXPECT_EQ(-0.25, Number::Cast(*value)->Value());
value = RoundTripTest(
Number::New(isolate(), std::numeric_limits<double>::quiet_NaN()));
ASSERT_TRUE(value->IsNumber());
EXPECT_TRUE(std::isnan(Number::Cast(*value)->Value()));
}
TEST_F(ValueSerializerTest, DecodeNumber) {
// 42 zig-zag encoded (signed)
DecodeTestFutureVersions({0xFF, 0x09, 0x49, 0x54}, [](Local<Value> value) {
ASSERT_TRUE(value->IsInt32());
EXPECT_EQ(42, Int32::Cast(*value)->Value());
});
// 42 varint encoded (unsigned)
DecodeTestFutureVersions({0xFF, 0x09, 0x55, 0x2A}, [](Local<Value> value) {
ASSERT_TRUE(value->IsInt32());
EXPECT_EQ(42, Int32::Cast(*value)->Value());
});
// 160 zig-zag encoded (signed)
DecodeTestFutureVersions({0xFF, 0x09, 0x49, 0xC0, 0x02},
[](Local<Value> value) {
ASSERT_TRUE(value->IsInt32());
ASSERT_EQ(160, Int32::Cast(*value)->Value());
});
// 160 varint encoded (unsigned)
DecodeTestFutureVersions({0xFF, 0x09, 0x55, 0xA0, 0x01},
[](Local<Value> value) {
ASSERT_TRUE(value->IsInt32());
ASSERT_EQ(160, Int32::Cast(*value)->Value());
});
#if defined(V8_TARGET_LITTLE_ENDIAN)
// IEEE 754 doubles, little-endian byte order
DecodeTestFutureVersions(
{0xFF, 0x09, 0x4E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xBF},
[](Local<Value> value) {
ASSERT_TRUE(value->IsNumber());
EXPECT_EQ(-0.25, Number::Cast(*value)->Value());
});
// quiet NaN
DecodeTestFutureVersions(
{0xFF, 0x09, 0x4E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x7F},
[](Local<Value> value) {
ASSERT_TRUE(value->IsNumber());
EXPECT_TRUE(std::isnan(Number::Cast(*value)->Value()));
});
// signaling NaN
DecodeTestFutureVersions(
{0xFF, 0x09, 0x4E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF4, 0x7F},
[](Local<Value> value) {
ASSERT_TRUE(value->IsNumber());
EXPECT_TRUE(std::isnan(Number::Cast(*value)->Value()));
});
#endif
// TODO(jbroman): Equivalent test for big-endian machines.
}
TEST_F(ValueSerializerTest, RoundTripBigInt) {
Local<Value> value = RoundTripTest(BigInt::New(isolate(), -42));
ASSERT_TRUE(value->IsBigInt());
ExpectScriptTrue("result === -42n");
value = RoundTripTest(BigInt::New(isolate(), 42));
ExpectScriptTrue("result === 42n");
value = RoundTripTest(BigInt::New(isolate(), 0));
ExpectScriptTrue("result === 0n");
value = RoundTripTest("0x1234567890abcdef777888999n");
ExpectScriptTrue("result === 0x1234567890abcdef777888999n");
value = RoundTripTest("-0x1234567890abcdef777888999123n");
ExpectScriptTrue("result === -0x1234567890abcdef777888999123n");
Context::Scope scope(serialization_context());
value = RoundTripTest(BigIntObject::New(isolate(), 23));
ASSERT_TRUE(value->IsBigIntObject());
ExpectScriptTrue("result == 23n");
}
TEST_F(ValueSerializerTest, DecodeBigInt) {
DecodeTestFutureVersions(
{
0xFF, 0x0D, // Version 13
0x5A, // BigInt
0x08, // Bitfield: sign = false, bytelength = 4
0x2A, 0x00, 0x00, 0x00, // Digit: 42
},
[this](Local<Value> value) {
ASSERT_TRUE(value->IsBigInt());
ExpectScriptTrue("result === 42n");
});
DecodeTestFutureVersions(
{
0xFF, 0x0D, // Version 13
0x7A, // BigIntObject
0x11, // Bitfield: sign = true, bytelength = 8
0x2A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // Digit: 42
},
[this](Local<Value> value) {
ASSERT_TRUE(value->IsBigIntObject());
ExpectScriptTrue("result == -42n");
});
DecodeTestFutureVersions(
{
0xFF, 0x0D, // Version 13
0x5A, // BigInt
0x10, // Bitfield: sign = false, bytelength = 8
0xEF, 0xCD, 0xAB, 0x90, 0x78, 0x56, 0x34, 0x12 // Digit(s).
},
[this](Local<Value> value) {
ExpectScriptTrue("result === 0x1234567890abcdefn");
});
DecodeTestFutureVersions(
{0xFF, 0x0D, // Version 13
0x5A, // BigInt
0x17, // Bitfield: sign = true, bytelength = 11
0xEF, 0xCD, 0xAB, 0x90, // Digits.
0x78, 0x56, 0x34, 0x12, 0x33, 0x44, 0x55},
[this](Local<Value> value) {
ExpectScriptTrue("result === -0x5544331234567890abcdefn");
});
DecodeTestFutureVersions(
{
0xFF, 0x0D, // Version 13
0x5A, // BigInt
0x02, // Bitfield: sign = false, bytelength = 1
0x2A, // Digit: 42
},
[this](Local<Value> value) { ExpectScriptTrue("result === 42n"); });
InvalidDecodeTest({
0xFF, 0x0F, // Version 15
0x5A, // BigInt
0x01, // Bitfield: sign = true, bytelength = 0
});
// From a philosophical standpoint, we could reject this case as invalid as
// well, but it would require extra code and probably isn't worth it, so
// we quietly normalize this invalid input to {0n}.
DecodeTestFutureVersions(
{
0xFF, 0x0F, // Version 15
0x5A, // BigInt
0x09, // Bitfield: sign = true, bytelength = 4
0x00, 0x00, 0x00, 0x00 // Digits.
},
[this](Local<Value> value) {
ExpectScriptTrue("(result | result) === 0n");
});
}
// String constants (in UTF-8) used for string encoding tests.
static const char kHelloString[] = "Hello";
static const char kQuebecString[] = "\x51\x75\xC3\xA9\x62\x65\x63";
static const char kEmojiString[] = "\xF0\x9F\x91\x8A";
TEST_F(ValueSerializerTest, RoundTripString) {
Local<Value> value = RoundTripTest(String::Empty(isolate()));
ASSERT_TRUE(value->IsString());
EXPECT_EQ(0, String::Cast(*value)->Length());
// Inside ASCII.
value = RoundTripTest(StringFromUtf8(kHelloString));
ASSERT_TRUE(value->IsString());
EXPECT_EQ(5, String::Cast(*value)->Length());
EXPECT_EQ(kHelloString, Utf8Value(value));
// Inside Latin-1 (i.e. one-byte string), but not ASCII.
value = RoundTripTest(StringFromUtf8(kQuebecString));
ASSERT_TRUE(value->IsString());
EXPECT_EQ(6, String::Cast(*value)->Length());
EXPECT_EQ(kQuebecString, Utf8Value(value));
// An emoji (decodes to two 16-bit chars).
value = RoundTripTest(StringFromUtf8(kEmojiString));
ASSERT_TRUE(value->IsString());
EXPECT_EQ(2, String::Cast(*value)->Length());
EXPECT_EQ(kEmojiString, Utf8Value(value));
}
TEST_F(ValueSerializerTest, DecodeString) {
// Decoding the strings above from UTF-8.
DecodeTestFutureVersions({0xFF, 0x09, 0x53, 0x00}, [](Local<Value> value) {
ASSERT_TRUE(value->IsString());
EXPECT_EQ(0, String::Cast(*value)->Length());
});
DecodeTestFutureVersions({0xFF, 0x09, 0x53, 0x05, 'H', 'e', 'l', 'l', 'o'},
[this](Local<Value> value) {
ASSERT_TRUE(value->IsString());
EXPECT_EQ(5, String::Cast(*value)->Length());
EXPECT_EQ(kHelloString, Utf8Value(value));
});
DecodeTestFutureVersions(
{0xFF, 0x09, 0x53, 0x07, 'Q', 'u', 0xC3, 0xA9, 'b', 'e', 'c'},
[this](Local<Value> value) {
ASSERT_TRUE(value->IsString());
EXPECT_EQ(6, String::Cast(*value)->Length());
EXPECT_EQ(kQuebecString, Utf8Value(value));
});
DecodeTestFutureVersions({0xFF, 0x09, 0x53, 0x04, 0xF0, 0x9F, 0x91, 0x8A},
[this](Local<Value> value) {
ASSERT_TRUE(value->IsString());
EXPECT_EQ(2, String::Cast(*value)->Length());
EXPECT_EQ(kEmojiString, Utf8Value(value));
});
// And from Latin-1 (for the ones that fit).
DecodeTestFutureVersions({0xFF, 0x0A, 0x22, 0x00}, [](Local<Value> value) {
ASSERT_TRUE(value->IsString());
EXPECT_EQ(0, String::Cast(*value)->Length());
});
DecodeTestFutureVersions({0xFF, 0x0A, 0x22, 0x05, 'H', 'e', 'l', 'l', 'o'},
[this](Local<Value> value) {
ASSERT_TRUE(value->IsString());
EXPECT_EQ(5, String::Cast(*value)->Length());
EXPECT_EQ(kHelloString, Utf8Value(value));
});
DecodeTestFutureVersions(
{0xFF, 0x0A, 0x22, 0x06, 'Q', 'u', 0xE9, 'b', 'e', 'c'},
[this](Local<Value> value) {
ASSERT_TRUE(value->IsString());
EXPECT_EQ(6, String::Cast(*value)->Length());
EXPECT_EQ(kQuebecString, Utf8Value(value));
});
// And from two-byte strings (endianness dependent).
#if defined(V8_TARGET_LITTLE_ENDIAN)
DecodeTestFutureVersions({0xFF, 0x09, 0x63, 0x00}, [](Local<Value> value) {
ASSERT_TRUE(value->IsString());
EXPECT_EQ(0, String::Cast(*value)->Length());
});
DecodeTestFutureVersions({0xFF, 0x09, 0x63, 0x0A, 'H', '\0', 'e', '\0', 'l',
'\0', 'l', '\0', 'o', '\0'},
[this](Local<Value> value) {
ASSERT_TRUE(value->IsString());
EXPECT_EQ(5, String::Cast(*value)->Length());
EXPECT_EQ(kHelloString, Utf8Value(value));
});
DecodeTestFutureVersions({0xFF, 0x09, 0x63, 0x0C, 'Q', '\0', 'u', '\0', 0xE9,
'\0', 'b', '\0', 'e', '\0', 'c', '\0'},
[this](Local<Value> value) {
ASSERT_TRUE(value->IsString());
EXPECT_EQ(6, String::Cast(*value)->Length());
EXPECT_EQ(kQuebecString, Utf8Value(value));
});
DecodeTestFutureVersions({0xFF, 0x09, 0x63, 0x04, 0x3D, 0xD8, 0x4A, 0xDC},
[this](Local<Value> value) {
ASSERT_TRUE(value->IsString());
EXPECT_EQ(2, String::Cast(*value)->Length());
EXPECT_EQ(kEmojiString, Utf8Value(value));
});
#endif
// TODO(jbroman): The same for big-endian systems.
}
TEST_F(ValueSerializerTest, DecodeInvalidString) {
// UTF-8 string with too few bytes available.
InvalidDecodeTest({0xFF, 0x09, 0x53, 0x10, 'v', '8'});
// One-byte string with too few bytes available.
InvalidDecodeTest({0xFF, 0x0A, 0x22, 0x10, 'v', '8'});
#if defined(V8_TARGET_LITTLE_ENDIAN)
// Two-byte string with too few bytes available.
InvalidDecodeTest({0xFF, 0x09, 0x63, 0x10, 'v', '\0', '8', '\0'});
// Two-byte string with an odd byte length.
InvalidDecodeTest({0xFF, 0x09, 0x63, 0x03, 'v', '\0', '8'});
#endif
// TODO(jbroman): The same for big-endian systems.
}
TEST_F(ValueSerializerTest, EncodeTwoByteStringUsesPadding) {
// As long as the output has a version that Blink expects to be able to read,
// we must respect its alignment requirements. It requires that two-byte
// characters be aligned.
// We need a string whose length will take two bytes to encode, so that
// a padding byte is needed to keep the characters aligned. The string
// must also have a two-byte character, so that it gets the two-byte
// encoding.
std::string string(200, ' ');
string += kEmojiString;
const std::vector<uint8_t> data = EncodeTest(StringFromUtf8(string.c_str()));
// This is a sufficient but not necessary condition. This test assumes
// that the wire format version is one byte long, but is flexible to
// what that value may be.
const uint8_t expected_prefix[] = {0x00, 0x63, 0x94, 0x03};
ASSERT_GT(data.size(), sizeof(expected_prefix) + 2);
EXPECT_EQ(0xFF, data[0]);
EXPECT_GE(data[1], 0x09);
EXPECT_LE(data[1], 0x7F);
EXPECT_TRUE(std::equal(std::begin(expected_prefix), std::end(expected_prefix),
data.begin() + 2));
}
TEST_F(ValueSerializerTest, RoundTripDictionaryObject) {
// Empty object.
Local<Value> value = RoundTripTest("({})");
ASSERT_TRUE(value->IsObject());
ExpectScriptTrue("Object.getPrototypeOf(result) === Object.prototype");
ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 0");
// String key.
value = RoundTripTest("({ a: 42 })");
ASSERT_TRUE(value->IsObject());
ExpectScriptTrue("result.hasOwnProperty('a')");
ExpectScriptTrue("result.a === 42");
ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 1");
// Integer key (treated as a string, but may be encoded differently).
value = RoundTripTest("({ 42: 'a' })");
ASSERT_TRUE(value->IsObject());
ExpectScriptTrue("result.hasOwnProperty('42')");
ExpectScriptTrue("result[42] === 'a'");
ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 1");
// Key order must be preserved.
value = RoundTripTest("({ x: 1, y: 2, a: 3 })");
ExpectScriptTrue("Object.getOwnPropertyNames(result).toString() === 'x,y,a'");
// A harder case of enumeration order.
// Indexes first, in order (but not 2^32 - 1, which is not an index), then the
// remaining (string) keys, in the order they were defined.
value = RoundTripTest("({ a: 2, 0xFFFFFFFF: 1, 0xFFFFFFFE: 3, 1: 0 })");
ExpectScriptTrue(
"Object.getOwnPropertyNames(result).toString() === "
"'1,4294967294,a,4294967295'");
ExpectScriptTrue("result.a === 2");
ExpectScriptTrue("result[0xFFFFFFFF] === 1");
ExpectScriptTrue("result[0xFFFFFFFE] === 3");
ExpectScriptTrue("result[1] === 0");
// This detects a fairly subtle case: the object itself must be in the map
// before its properties are deserialized, so that references to it can be
// resolved.
value = RoundTripTest("var y = {}; y.self = y; y;");
ASSERT_TRUE(value->IsObject());
ExpectScriptTrue("result === result.self");
}
TEST_F(ValueSerializerTest, DecodeDictionaryObject) {
// Empty object.
DecodeTestFutureVersions(
{0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x7B, 0x00, 0x00},
[this](Local<Value> value) {
ASSERT_TRUE(value->IsObject());
ExpectScriptTrue("Object.getPrototypeOf(result) === Object.prototype");
ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 0");
});
// String key.
DecodeTestFutureVersions(
{0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x53, 0x01, 0x61, 0x3F, 0x01,
0x49, 0x54, 0x7B, 0x01},
[this](Local<Value> value) {
ASSERT_TRUE(value->IsObject());
ExpectScriptTrue("result.hasOwnProperty('a')");
ExpectScriptTrue("result.a === 42");
ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 1");
});
// Integer key (treated as a string, but may be encoded differently).
DecodeTestFutureVersions(
{0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x49, 0x54, 0x3F, 0x01, 0x53,
0x01, 0x61, 0x7B, 0x01},
[this](Local<Value> value) {
ASSERT_TRUE(value->IsObject());
ExpectScriptTrue("result.hasOwnProperty('42')");
ExpectScriptTrue("result[42] === 'a'");
ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 1");
});
// Key order must be preserved.
DecodeTestFutureVersions(
{0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x53, 0x01, 0x78, 0x3F, 0x01,
0x49, 0x02, 0x3F, 0x01, 0x53, 0x01, 0x79, 0x3F, 0x01, 0x49, 0x04, 0x3F,
0x01, 0x53, 0x01, 0x61, 0x3F, 0x01, 0x49, 0x06, 0x7B, 0x03},
[this](Local<Value> value) {
ExpectScriptTrue(
"Object.getOwnPropertyNames(result).toString() === 'x,y,a'");
});
// A harder case of enumeration order.
DecodeTestFutureVersions(
{0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x49, 0x02, 0x3F, 0x01,
0x49, 0x00, 0x3F, 0x01, 0x55, 0xFE, 0xFF, 0xFF, 0xFF, 0x0F, 0x3F,
0x01, 0x49, 0x06, 0x3F, 0x01, 0x53, 0x01, 0x61, 0x3F, 0x01, 0x49,
0x04, 0x3F, 0x01, 0x53, 0x0A, 0x34, 0x32, 0x39, 0x34, 0x39, 0x36,
0x37, 0x32, 0x39, 0x35, 0x3F, 0x01, 0x49, 0x02, 0x7B, 0x04},
[this](Local<Value> value) {
ExpectScriptTrue(
"Object.getOwnPropertyNames(result).toString() === "
"'1,4294967294,a,4294967295'");
ExpectScriptTrue("result.a === 2");
ExpectScriptTrue("result[0xFFFFFFFF] === 1");
ExpectScriptTrue("result[0xFFFFFFFE] === 3");
ExpectScriptTrue("result[1] === 0");
});
// This detects a fairly subtle case: the object itself must be in the map
// before its properties are deserialized, so that references to it can be
// resolved.
DecodeTestFutureVersions(
{0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x53, 0x04, 0x73,
0x65, 0x6C, 0x66, 0x3F, 0x01, 0x5E, 0x00, 0x7B, 0x01, 0x00},
[this](Local<Value> value) {
ASSERT_TRUE(value->IsObject());
ExpectScriptTrue("result === result.self");
});
}
TEST_F(ValueSerializerTest, InvalidDecodeObjectWithInvalidKeyType) {
// Objects which would need conversion to string shouldn't be present as
// object keys. The serializer would have obtained them from the own property
// keys list, which should only contain names and indices.
InvalidDecodeTest(
{0xFF, 0x09, 0x6F, 0x61, 0x00, 0x40, 0x00, 0x00, 0x7B, 0x01});
}
TEST_F(ValueSerializerTest, RoundTripOnlyOwnEnumerableStringKeys) {
// Only "own" properties should be serialized, not ones on the prototype.
Local<Value> value = RoundTripTest("var x = {}; x.__proto__ = {a: 4}; x;");
ExpectScriptTrue("!('a' in result)");
// Only enumerable properties should be serialized.
value = RoundTripTest(
"var x = {};"
"Object.defineProperty(x, 'a', {value: 1, enumerable: false});"
"x;");
ExpectScriptTrue("!('a' in result)");
// Symbol keys should not be serialized.
value = RoundTripTest("({ [Symbol()]: 4 })");
ExpectScriptTrue("Object.getOwnPropertySymbols(result).length === 0");
}
TEST_F(ValueSerializerTest, RoundTripTrickyGetters) {
// Keys are enumerated before any setters are called, but if there is no own
// property when the value is to be read, then it should not be serialized.
Local<Value> value =
RoundTripTest("({ get a() { delete this.b; return 1; }, b: 2 })");
ExpectScriptTrue("!('b' in result)");
// Keys added after the property enumeration should not be serialized.
value = RoundTripTest("({ get a() { this.b = 3; }})");
ExpectScriptTrue("!('b' in result)");
// But if you remove a key and add it back, that's fine. But it will appear in
// the original place in enumeration order.
value =
RoundTripTest("({ get a() { delete this.b; this.b = 4; }, b: 2, c: 3 })");
ExpectScriptTrue("Object.getOwnPropertyNames(result).toString() === 'a,b,c'");
ExpectScriptTrue("result.b === 4");
// Similarly, it only matters if a property was enumerable when the
// enumeration happened.
value = RoundTripTest(
"({ get a() {"
" Object.defineProperty(this, 'b', {value: 2, enumerable: false});"
"}, b: 1})");
ExpectScriptTrue("result.b === 2");
value = RoundTripTest(
"var x = {"
" get a() {"
" Object.defineProperty(this, 'b', {value: 2, enumerable: true});"
" }"
"};"
"Object.defineProperty(x, 'b',"
" {value: 1, enumerable: false, configurable: true});"
"x;");
ExpectScriptTrue("!('b' in result)");
// The property also should not be read if it can only be found on the
// prototype chain (but not as an own property) after enumeration.
value = RoundTripTest(
"var x = { get a() { delete this.b; }, b: 1 };"
"x.__proto__ = { b: 0 };"
"x;");
ExpectScriptTrue("!('b' in result)");
// If an exception is thrown by script, encoding must fail and the exception
// must be thrown.
Local<Message> message =
InvalidEncodeTest("({ get a() { throw new Error('sentinel'); } })");
ASSERT_FALSE(message.IsEmpty());
EXPECT_NE(std::string::npos, Utf8Value(message->Get()).find("sentinel"));
}
TEST_F(ValueSerializerTest, RoundTripDictionaryObjectForTransitions) {
// A case which should run on the fast path, and should reach all of the
// different cases:
// 1. no known transition (first time creating this kind of object)
// 2. expected transitions match to end
// 3. transition partially matches, but falls back due to new property 'w'
// 4. transition to 'z' is now a full transition (needs to be looked up)
// 5. same for 'w'
// 6. new property after complex transition succeeded
// 7. new property after complex transition failed (due to new property)
RoundTripJSON(
"[{\"x\":1,\"y\":2,\"z\":3}"
",{\"x\":4,\"y\":5,\"z\":6}"
",{\"x\":5,\"y\":6,\"w\":7}"
",{\"x\":6,\"y\":7,\"z\":8}"
",{\"x\":0,\"y\":0,\"w\":0}"
",{\"x\":3,\"y\":1,\"w\":4,\"z\":1}"
",{\"x\":5,\"y\":9,\"k\":2,\"z\":6}]");
// A simpler case that uses two-byte strings.
RoundTripJSON(
"[{\"\xF0\x9F\x91\x8A\":1,\"\xF0\x9F\x91\x8B\":2}"
",{\"\xF0\x9F\x91\x8A\":3,\"\xF0\x9F\x91\x8C\":4}"
",{\"\xF0\x9F\x91\x8A\":5,\"\xF0\x9F\x91\x9B\":6}]");
}
TEST_F(ValueSerializerTest, DecodeDictionaryObjectVersion0) {
// Empty object.
Local<Value> value = DecodeTestForVersion0({0x7B, 0x00});
ASSERT_TRUE(value->IsObject());
ExpectScriptTrue("Object.getPrototypeOf(result) === Object.prototype");
ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 0");
// String key.
value =
DecodeTestForVersion0({0x53, 0x01, 0x61, 0x49, 0x54, 0x7B, 0x01, 0x00});
ASSERT_TRUE(value->IsObject());
ExpectScriptTrue("Object.getPrototypeOf(result) === Object.prototype");
ExpectScriptTrue("result.hasOwnProperty('a')");