value-serializer-unittest.cc 111 KB
Newer Older
1 2 3 4
// 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.

5
#include "src/objects/value-serializer.h"
6

7 8 9
#include <algorithm>
#include <string>

10
#include "include/v8.h"
11
#include "src/api/api-inl.h"
12
#include "src/base/build_config.h"
13
#include "src/objects/backing-store.h"
14
#include "src/objects/objects-inl.h"
15 16 17
#include "test/unittests/test-utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
18

19 20 21 22 23 24
#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

25 26 27
namespace v8 {
namespace {

28 29
using ::testing::_;
using ::testing::Invoke;
30
using ::testing::Return;
31

32
class ValueSerializerTest : public TestWithIsolate {
33 34 35 36
 public:
  ValueSerializerTest(const ValueSerializerTest&) = delete;
  ValueSerializerTest& operator=(const ValueSerializerTest&) = delete;

37 38 39
 protected:
  ValueSerializerTest()
      : serialization_context_(Context::New(isolate())),
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
        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;
68 69 70
    isolate_ = reinterpret_cast<i::Isolate*>(isolate());
  }

71
  ~ValueSerializerTest() override {
72 73 74 75 76 77 78
    // 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();
    }
79
  }
80 81 82 83 84 85 86 87

  const Local<Context>& serialization_context() {
    return serialization_context_;
  }
  const Local<Context>& deserialization_context() {
    return deserialization_context_;
  }

88
  // Overridden in more specific fixtures.
89
  virtual ValueSerializer::Delegate* GetSerializerDelegate() { return nullptr; }
90
  virtual void BeforeEncode(ValueSerializer*) {}
91 92 93
  virtual ValueDeserializer::Delegate* GetDeserializerDelegate() {
    return nullptr;
  }
94 95
  virtual void BeforeDecode(ValueDeserializer*) {}

96 97 98
  Local<Value> RoundTripTest(Local<Value> input_value) {
    std::vector<uint8_t> encoded = EncodeTest(input_value);
    return DecodeTest(encoded);
99 100
  }

101 102
  // Variant for the common case where a script is used to build the original
  // value.
103 104
  Local<Value> RoundTripTest(const char* source) {
    return RoundTripTest(EvaluateScriptForInput(source));
105 106
  }

107 108
  // Variant which uses JSON.parse/stringify to check the result.
  void RoundTripJSON(const char* source) {
109 110 111 112 113 114 115 116
    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()));
117 118
  }

119
  Maybe<std::vector<uint8_t>> DoEncode(Local<Value> value) {
120
    Local<Context> context = serialization_context();
121
    ValueSerializer serializer(isolate(), GetSerializerDelegate());
122
    BeforeEncode(&serializer);
123
    serializer.WriteHeader();
124 125
    if (!serializer.WriteValue(context, value).FromMaybe(false)) {
      return Nothing<std::vector<uint8_t>>();
126
    }
127 128
    std::pair<uint8_t*, size_t> buffer = serializer.Release();
    std::vector<uint8_t> result(buffer.first, buffer.first + buffer.second);
129 130 131 132
    if (auto* delegate = GetSerializerDelegate())
      delegate->FreeBufferMemory(buffer.first);
    else
      free(buffer.first);
133
    return Just(std::move(result));
134 135
  }

136
  std::vector<uint8_t> EncodeTest(Local<Value> input_value) {
137 138
    Context::Scope scope(serialization_context());
    TryCatch try_catch(isolate());
139
    std::vector<uint8_t> buffer;
140 141 142 143 144 145 146 147 148
    // 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;
149 150
  }

151 152 153 154
  std::vector<uint8_t> EncodeTest(const char* source) {
    return EncodeTest(EvaluateScriptForInput(source));
  }

155
  v8::Local<v8::Message> InvalidEncodeTest(Local<Value> input_value) {
156 157
    Context::Scope scope(serialization_context());
    TryCatch try_catch(isolate());
158 159
    CHECK(DoEncode(input_value).IsNothing());
    return try_catch.Message();
160 161
  }

162 163
  v8::Local<v8::Message> InvalidEncodeTest(const char* source) {
    return InvalidEncodeTest(EvaluateScriptForInput(source));
164 165
  }

166
  Local<Value> DecodeTest(const std::vector<uint8_t>& data) {
167 168
    Local<Context> context = deserialization_context();
    Context::Scope scope(context);
169
    TryCatch try_catch(isolate());
170
    ValueDeserializer deserializer(isolate(), &data[0],
171 172
                                   static_cast<int>(data.size()),
                                   GetDeserializerDelegate());
173
    deserializer.SetSupportsLegacyWireFormat(true);
174
    BeforeDecode(&deserializer);
175
    CHECK(deserializer.ReadHeader(context).FromMaybe(false));
176
    Local<Value> result;
177 178 179 180 181 182 183 184
    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;
185 186
  }

187
  Local<Value> DecodeTestForVersion0(const std::vector<uint8_t>& data) {
188 189
    Local<Context> context = deserialization_context();
    Context::Scope scope(context);
190
    TryCatch try_catch(isolate());
191
    ValueDeserializer deserializer(isolate(), &data[0],
192 193
                                   static_cast<int>(data.size()),
                                   GetDeserializerDelegate());
194
    deserializer.SetSupportsLegacyWireFormat(true);
195
    BeforeDecode(&deserializer);
196 197
    CHECK(deserializer.ReadHeader(context).FromMaybe(false));
    CHECK_EQ(0u, deserializer.GetWireFormatVersion());
198
    Local<Value> result;
199 200 201 202 203 204 205 206
    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;
207 208
  }

209
  void InvalidDecodeTest(const std::vector<uint8_t>& data) {
210 211
    Local<Context> context = deserialization_context();
    Context::Scope scope(context);
212
    TryCatch try_catch(isolate());
213
    ValueDeserializer deserializer(isolate(), &data[0],
214 215
                                   static_cast<int>(data.size()),
                                   GetDeserializerDelegate());
216
    deserializer.SetSupportsLegacyWireFormat(true);
217
    BeforeDecode(&deserializer);
218 219 220 221 222
    Maybe<bool> header_result = deserializer.ReadHeader(context);
    if (header_result.IsNothing()) {
      EXPECT_TRUE(try_catch.HasCaught());
      return;
    }
223 224
    CHECK(header_result.ToChecked());
    CHECK(deserializer.ReadValue(context).IsEmpty());
225
    EXPECT_TRUE(try_catch.HasCaught());
226 227 228
  }

  Local<Value> EvaluateScriptForInput(const char* utf8_source) {
229
    Context::Scope scope(serialization_context_);
230 231 232 233 234 235
    Local<String> source = StringFromUtf8(utf8_source);
    Local<Script> script =
        Script::Compile(serialization_context_, source).ToLocalChecked();
    return script->Run(serialization_context_).ToLocalChecked();
  }

236 237
  void ExpectScriptTrue(const char* utf8_source) {
    Context::Scope scope(deserialization_context_);
238 239 240 241
    Local<String> source = StringFromUtf8(utf8_source);
    Local<Script> script =
        Script::Compile(deserialization_context_, source).ToLocalChecked();
    Local<Value> value = script->Run(deserialization_context_).ToLocalChecked();
242
    EXPECT_TRUE(value->BooleanValue(isolate()));
243 244 245
  }

  Local<String> StringFromUtf8(const char* source) {
246
    return String::NewFromUtf8(isolate(), source).ToLocalChecked();
247 248
  }

249 250
  std::string Utf8Value(Local<Value> value) {
    String::Utf8Value utf8(isolate(), value);
251 252 253
    return std::string(*utf8, utf8.length());
  }

254 255 256 257 258 259 260 261
  Local<Object> NewHostObject(Local<Context> context, int argc,
                              Local<Value> argv[]) {
    return host_object_constructor_template_->GetFunction(context)
        .ToLocalChecked()
        ->NewInstance(context, argc, argv)
        .ToLocalChecked();
  }

262 263
  Local<Object> NewDummyUint8Array() {
    static uint8_t data[] = {4, 5, 6};
264 265 266
    std::unique_ptr<v8::BackingStore> backing_store =
        ArrayBuffer::NewBackingStore(
            data, sizeof(data), [](void*, size_t, void*) {}, nullptr);
267
    Local<ArrayBuffer> ab =
268
        ArrayBuffer::New(isolate(), std::move(backing_store));
269 270 271
    return Uint8Array::New(ab, 0, sizeof(data));
  }

272 273 274
 private:
  Local<Context> serialization_context_;
  Local<Context> deserialization_context_;
275
  Local<FunctionTemplate> host_object_constructor_template_;
276
  i::Isolate* isolate_;
277 278 279 280
};

TEST_F(ValueSerializerTest, DecodeInvalid) {
  // Version tag but no content.
281
  InvalidDecodeTest({0xFF});
282
  // Version too large.
283
  InvalidDecodeTest({0xFF, 0x7F, 0x5F});
284
  // Nonsense tag.
285
  InvalidDecodeTest({0xFF, 0x09, 0xDD});
286 287 288
}

TEST_F(ValueSerializerTest, RoundTripOddball) {
289 290 291 292 293 294 295 296
  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());
297 298 299 300
}

TEST_F(ValueSerializerTest, DecodeOddball) {
  // What this code is expected to generate.
301 302 303 304 305 306 307 308
  Local<Value> value = DecodeTest({0xFF, 0x09, 0x5F});
  EXPECT_TRUE(value->IsUndefined());
  value = DecodeTest({0xFF, 0x09, 0x54});
  EXPECT_TRUE(value->IsTrue());
  value = DecodeTest({0xFF, 0x09, 0x46});
  EXPECT_TRUE(value->IsFalse());
  value = DecodeTest({0xFF, 0x09, 0x30});
  EXPECT_TRUE(value->IsNull());
309 310

  // What v9 of the Blink code generates.
311 312 313 314 315 316 317 318
  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());
319 320

  // v0 (with no explicit version).
321 322 323 324 325 326 327 328
  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());
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
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);
}

414
TEST_F(ValueSerializerTest, RoundTripNumber) {
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
  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()));
436 437 438 439
}

TEST_F(ValueSerializerTest, DecodeNumber) {
  // 42 zig-zag encoded (signed)
440 441 442 443
  Local<Value> value = DecodeTest({0xFF, 0x09, 0x49, 0x54});
  ASSERT_TRUE(value->IsInt32());
  EXPECT_EQ(42, Int32::Cast(*value)->Value());

444
  // 42 varint encoded (unsigned)
445 446 447 448
  value = DecodeTest({0xFF, 0x09, 0x55, 0x2A});
  ASSERT_TRUE(value->IsInt32());
  EXPECT_EQ(42, Int32::Cast(*value)->Value());

449
  // 160 zig-zag encoded (signed)
450 451 452 453
  value = DecodeTest({0xFF, 0x09, 0x49, 0xC0, 0x02});
  ASSERT_TRUE(value->IsInt32());
  ASSERT_EQ(160, Int32::Cast(*value)->Value());

454
  // 160 varint encoded (unsigned)
455 456 457 458
  value = DecodeTest({0xFF, 0x09, 0x55, 0xA0, 0x01});
  ASSERT_TRUE(value->IsInt32());
  ASSERT_EQ(160, Int32::Cast(*value)->Value());

459 460
#if defined(V8_TARGET_LITTLE_ENDIAN)
  // IEEE 754 doubles, little-endian byte order
461 462 463 464 465
  value = DecodeTest(
      {0xFF, 0x09, 0x4E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xBF});
  ASSERT_TRUE(value->IsNumber());
  EXPECT_EQ(-0.25, Number::Cast(*value)->Value());

466
  // quiet NaN
467 468 469 470 471
  value = DecodeTest(
      {0xFF, 0x09, 0x4E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF8, 0x7F});
  ASSERT_TRUE(value->IsNumber());
  EXPECT_TRUE(std::isnan(Number::Cast(*value)->Value()));

472
  // signaling NaN
473 474 475 476
  value = DecodeTest(
      {0xFF, 0x09, 0x4E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF4, 0x7F});
  ASSERT_TRUE(value->IsNumber());
  EXPECT_TRUE(std::isnan(Number::Cast(*value)->Value()));
477 478 479 480
#endif
  // TODO(jbroman): Equivalent test for big-endian machines.
}

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
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) {
  Local<Value> value = DecodeTest({
      0xFF, 0x0D,              // Version 13
      0x5A,                    // BigInt
      0x08,                    // Bitfield: sign = false, bytelength = 4
      0x2A, 0x00, 0x00, 0x00,  // Digit: 42
  });
  ASSERT_TRUE(value->IsBigInt());
  ExpectScriptTrue("result === 42n");

  value = DecodeTest({
      0xFF, 0x0D,  // Version 13
      0x7A,        // BigIntObject
      0x11,        // Bitfield: sign = true, bytelength = 8
      0x2A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00  // Digit: 42
  });
  ASSERT_TRUE(value->IsBigIntObject());
  ExpectScriptTrue("result == -42n");

  value = DecodeTest({
      0xFF, 0x0D,  // Version 13
      0x5A,        // BigInt
      0x10,        // Bitfield: sign = false, bytelength = 8
      0xEF, 0xCD, 0xAB, 0x90, 0x78, 0x56, 0x34, 0x12  // Digit(s).
  });
  ExpectScriptTrue("result === 0x1234567890abcdefn");

  value = DecodeTest({0xFF, 0x0D,  // Version 13
                      0x5A,        // BigInt
                      0x17,        // Bitfield: sign = true, bytelength = 11
                      0xEF, 0xCD, 0xAB, 0x90,  // Digits.
                      0x78, 0x56, 0x34, 0x12, 0x33, 0x44, 0x55});
  ExpectScriptTrue("result === -0x5544331234567890abcdefn");

  value = DecodeTest({
      0xFF, 0x0D,  // Version 13
      0x5A,        // BigInt
      0x02,        // Bitfield: sign = false, bytelength = 1
      0x2A,        // Digit: 42
  });
  ExpectScriptTrue("result === 42n");
}

547 548 549 550 551 552
// 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) {
553 554 555 556
  Local<Value> value = RoundTripTest(String::Empty(isolate()));
  ASSERT_TRUE(value->IsString());
  EXPECT_EQ(0, String::Cast(*value)->Length());

557
  // Inside ASCII.
558 559 560 561 562
  value = RoundTripTest(StringFromUtf8(kHelloString));
  ASSERT_TRUE(value->IsString());
  EXPECT_EQ(5, String::Cast(*value)->Length());
  EXPECT_EQ(kHelloString, Utf8Value(value));

563
  // Inside Latin-1 (i.e. one-byte string), but not ASCII.
564 565 566 567 568
  value = RoundTripTest(StringFromUtf8(kQuebecString));
  ASSERT_TRUE(value->IsString());
  EXPECT_EQ(6, String::Cast(*value)->Length());
  EXPECT_EQ(kQuebecString, Utf8Value(value));

569
  // An emoji (decodes to two 16-bit chars).
570 571 572 573
  value = RoundTripTest(StringFromUtf8(kEmojiString));
  ASSERT_TRUE(value->IsString());
  EXPECT_EQ(2, String::Cast(*value)->Length());
  EXPECT_EQ(kEmojiString, Utf8Value(value));
574 575 576 577
}

TEST_F(ValueSerializerTest, DecodeString) {
  // Decoding the strings above from UTF-8.
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
  Local<Value> value = DecodeTest({0xFF, 0x09, 0x53, 0x00});
  ASSERT_TRUE(value->IsString());
  EXPECT_EQ(0, String::Cast(*value)->Length());

  value = DecodeTest({0xFF, 0x09, 0x53, 0x05, 'H', 'e', 'l', 'l', 'o'});
  ASSERT_TRUE(value->IsString());
  EXPECT_EQ(5, String::Cast(*value)->Length());
  EXPECT_EQ(kHelloString, Utf8Value(value));

  value =
      DecodeTest({0xFF, 0x09, 0x53, 0x07, 'Q', 'u', 0xC3, 0xA9, 'b', 'e', 'c'});
  ASSERT_TRUE(value->IsString());
  EXPECT_EQ(6, String::Cast(*value)->Length());
  EXPECT_EQ(kQuebecString, Utf8Value(value));

  value = DecodeTest({0xFF, 0x09, 0x53, 0x04, 0xF0, 0x9F, 0x91, 0x8A});
  ASSERT_TRUE(value->IsString());
  EXPECT_EQ(2, String::Cast(*value)->Length());
  EXPECT_EQ(kEmojiString, Utf8Value(value));
597

598
  // And from Latin-1 (for the ones that fit).
599 600 601 602 603 604 605 606 607 608 609 610 611
  value = DecodeTest({0xFF, 0x0A, 0x22, 0x00});
  ASSERT_TRUE(value->IsString());
  EXPECT_EQ(0, String::Cast(*value)->Length());

  value = DecodeTest({0xFF, 0x0A, 0x22, 0x05, 'H', 'e', 'l', 'l', 'o'});
  ASSERT_TRUE(value->IsString());
  EXPECT_EQ(5, String::Cast(*value)->Length());
  EXPECT_EQ(kHelloString, Utf8Value(value));

  value = DecodeTest({0xFF, 0x0A, 0x22, 0x06, 'Q', 'u', 0xE9, 'b', 'e', 'c'});
  ASSERT_TRUE(value->IsString());
  EXPECT_EQ(6, String::Cast(*value)->Length());
  EXPECT_EQ(kQuebecString, Utf8Value(value));
612

613 614
// And from two-byte strings (endianness dependent).
#if defined(V8_TARGET_LITTLE_ENDIAN)
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
  value = DecodeTest({0xFF, 0x09, 0x63, 0x00});
  ASSERT_TRUE(value->IsString());
  EXPECT_EQ(0, String::Cast(*value)->Length());

  value = DecodeTest({0xFF, 0x09, 0x63, 0x0A, 'H', '\0', 'e', '\0', 'l', '\0',
                      'l', '\0', 'o', '\0'});
  ASSERT_TRUE(value->IsString());
  EXPECT_EQ(5, String::Cast(*value)->Length());
  EXPECT_EQ(kHelloString, Utf8Value(value));

  value = DecodeTest({0xFF, 0x09, 0x63, 0x0C, 'Q', '\0', 'u', '\0', 0xE9, '\0',
                      'b', '\0', 'e', '\0', 'c', '\0'});
  ASSERT_TRUE(value->IsString());
  EXPECT_EQ(6, String::Cast(*value)->Length());
  EXPECT_EQ(kQuebecString, Utf8Value(value));

  value = DecodeTest({0xFF, 0x09, 0x63, 0x04, 0x3D, 0xD8, 0x4A, 0xDC});
  ASSERT_TRUE(value->IsString());
  EXPECT_EQ(2, String::Cast(*value)->Length());
  EXPECT_EQ(kEmojiString, Utf8Value(value));
635 636 637 638 639 640
#endif
  // TODO(jbroman): The same for big-endian systems.
}

TEST_F(ValueSerializerTest, DecodeInvalidString) {
  // UTF-8 string with too few bytes available.
641
  InvalidDecodeTest({0xFF, 0x09, 0x53, 0x10, 'v', '8'});
642
  // One-byte string with too few bytes available.
643
  InvalidDecodeTest({0xFF, 0x0A, 0x22, 0x10, 'v', '8'});
644 645
#if defined(V8_TARGET_LITTLE_ENDIAN)
  // Two-byte string with too few bytes available.
646
  InvalidDecodeTest({0xFF, 0x09, 0x63, 0x10, 'v', '\0', '8', '\0'});
647
  // Two-byte string with an odd byte length.
648
  InvalidDecodeTest({0xFF, 0x09, 0x63, 0x03, 'v', '\0', '8'});
649 650 651 652 653 654 655 656
#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.
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
  // 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));
674 675
}

676 677
TEST_F(ValueSerializerTest, RoundTripDictionaryObject) {
  // Empty object.
678 679 680 681 682
  Local<Value> value = RoundTripTest("({})");
  ASSERT_TRUE(value->IsObject());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Object.prototype");
  ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 0");

683
  // String key.
684 685 686 687 688 689
  value = RoundTripTest("({ a: 42 })");
  ASSERT_TRUE(value->IsObject());
  ExpectScriptTrue("result.hasOwnProperty('a')");
  ExpectScriptTrue("result.a === 42");
  ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 1");

690
  // Integer key (treated as a string, but may be encoded differently).
691 692 693 694 695 696
  value = RoundTripTest("({ 42: 'a' })");
  ASSERT_TRUE(value->IsObject());
  ExpectScriptTrue("result.hasOwnProperty('42')");
  ExpectScriptTrue("result[42] === 'a'");
  ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 1");

697
  // Key order must be preserved.
698 699 700
  value = RoundTripTest("({ x: 1, y: 2, a: 3 })");
  ExpectScriptTrue("Object.getOwnPropertyNames(result).toString() === 'x,y,a'");

701 702 703
  // 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.
704 705 706 707 708 709 710 711 712
  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");

713 714 715
  // 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.
716 717 718
  value = RoundTripTest("var y = {}; y.self = y; y;");
  ASSERT_TRUE(value->IsObject());
  ExpectScriptTrue("result === result.self");
719 720 721 722
}

TEST_F(ValueSerializerTest, DecodeDictionaryObject) {
  // Empty object.
723 724 725 726 727 728
  Local<Value> value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x7B, 0x00, 0x00});
  ASSERT_TRUE(value->IsObject());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Object.prototype");
  ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 0");

729
  // String key.
730 731 732 733 734 735 736
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x53, 0x01,
                      0x61, 0x3F, 0x01, 0x49, 0x54, 0x7B, 0x01});
  ASSERT_TRUE(value->IsObject());
  ExpectScriptTrue("result.hasOwnProperty('a')");
  ExpectScriptTrue("result.a === 42");
  ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 1");

737
  // Integer key (treated as a string, but may be encoded differently).
738 739 740 741 742 743 744
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x49, 0x54,
                      0x3F, 0x01, 0x53, 0x01, 0x61, 0x7B, 0x01});
  ASSERT_TRUE(value->IsObject());
  ExpectScriptTrue("result.hasOwnProperty('42')");
  ExpectScriptTrue("result[42] === 'a'");
  ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 1");

745
  // Key order must be preserved.
746 747 748 749 750 751
  value = DecodeTest({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});
  ExpectScriptTrue("Object.getOwnPropertyNames(result).toString() === 'x,y,a'");

752
  // A harder case of enumeration order.
753 754 755 756 757 758 759 760 761 762 763 764 765 766
  value = DecodeTest({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});
  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");

767 768 769
  // 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.
770 771 772 773 774
  value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x53, 0x04, 0x73,
                  0x65, 0x6C, 0x66, 0x3F, 0x01, 0x5E, 0x00, 0x7B, 0x01, 0x00});
  ASSERT_TRUE(value->IsObject());
  ExpectScriptTrue("result === result.self");
775 776
}

777 778 779 780 781
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(
782
      {0xFF, 0x09, 0x6F, 0x61, 0x00, 0x40, 0x00, 0x00, 0x7B, 0x01});
783 784
}

785 786
TEST_F(ValueSerializerTest, RoundTripOnlyOwnEnumerableStringKeys) {
  // Only "own" properties should be serialized, not ones on the prototype.
787 788 789
  Local<Value> value = RoundTripTest("var x = {}; x.__proto__ = {a: 4}; x;");
  ExpectScriptTrue("!('a' in result)");

790
  // Only enumerable properties should be serialized.
791 792 793 794 795 796
  value = RoundTripTest(
      "var x = {};"
      "Object.defineProperty(x, 'a', {value: 1, enumerable: false});"
      "x;");
  ExpectScriptTrue("!('a' in result)");

797
  // Symbol keys should not be serialized.
798 799
  value = RoundTripTest("({ [Symbol()]: 4 })");
  ExpectScriptTrue("Object.getOwnPropertySymbols(result).length === 0");
800 801 802 803 804
}

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.
805 806 807 808
  Local<Value> value =
      RoundTripTest("({ get a() { delete this.b; return 1; }, b: 2 })");
  ExpectScriptTrue("!('b' in result)");

809
  // Keys added after the property enumeration should not be serialized.
810 811 812
  value = RoundTripTest("({ get a() { this.b = 3; }})");
  ExpectScriptTrue("!('b' in result)");

813 814
  // But if you remove a key and add it back, that's fine. But it will appear in
  // the original place in enumeration order.
815 816 817 818 819
  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");

820 821
  // Similarly, it only matters if a property was enumerable when the
  // enumeration happened.
822
  value = RoundTripTest(
823 824
      "({ get a() {"
      "    Object.defineProperty(this, 'b', {value: 2, enumerable: false});"
825 826 827 828 829 830 831 832 833 834 835 836 837 838
      "}, 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)");

839 840
  // 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.
841 842 843 844 845 846
  value = RoundTripTest(
      "var x = { get a() { delete this.b; }, b: 1 };"
      "x.__proto__ = { b: 0 };"
      "x;");
  ExpectScriptTrue("!('b' in result)");

847 848
  // If an exception is thrown by script, encoding must fail and the exception
  // must be thrown.
849 850 851 852
  Local<Message> message =
      InvalidEncodeTest("({ get a() { throw new Error('sentinel'); } })");
  ASSERT_FALSE(message.IsEmpty());
  EXPECT_NE(std::string::npos, Utf8Value(message->Get()).find("sentinel"));
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
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}]");
}

880 881
TEST_F(ValueSerializerTest, DecodeDictionaryObjectVersion0) {
  // Empty object.
882 883 884 885 886
  Local<Value> value = DecodeTestForVersion0({0x7B, 0x00});
  ASSERT_TRUE(value->IsObject());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Object.prototype");
  ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 0");

887
  // String key.
888 889 890 891 892 893 894 895
  value =
      DecodeTestForVersion0({0x53, 0x01, 0x61, 0x49, 0x54, 0x7B, 0x01, 0x00});
  ASSERT_TRUE(value->IsObject());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Object.prototype");
  ExpectScriptTrue("result.hasOwnProperty('a')");
  ExpectScriptTrue("result.a === 42");
  ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 1");

896
  // Integer key (treated as a string, but may be encoded differently).
897 898 899 900 901 902 903
  value =
      DecodeTestForVersion0({0x49, 0x54, 0x53, 0x01, 0x61, 0x7B, 0x01, 0x00});
  ASSERT_TRUE(value->IsObject());
  ExpectScriptTrue("result.hasOwnProperty('42')");
  ExpectScriptTrue("result[42] === 'a'");
  ExpectScriptTrue("Object.getOwnPropertyNames(result).length === 1");

904
  // Key order must be preserved.
905 906 907 908 909
  value = DecodeTestForVersion0({0x53, 0x01, 0x78, 0x49, 0x02, 0x53, 0x01, 0x79,
                                 0x49, 0x04, 0x53, 0x01, 0x61, 0x49, 0x06, 0x7B,
                                 0x03, 0x00});
  ExpectScriptTrue("Object.getOwnPropertyNames(result).toString() === 'x,y,a'");

910
  // A property and an element.
911 912 913 914 915
  value = DecodeTestForVersion0(
      {0x49, 0x54, 0x53, 0x01, 0x61, 0x53, 0x01, 0x61, 0x49, 0x54, 0x7B, 0x02});
  ExpectScriptTrue("Object.getOwnPropertyNames(result).toString() === '42,a'");
  ExpectScriptTrue("result[42] === 'a'");
  ExpectScriptTrue("result.a === 42");
916 917
}

918 919
TEST_F(ValueSerializerTest, RoundTripArray) {
  // A simple array of integers.
920 921 922 923 924 925
  Local<Value> value = RoundTripTest("[1, 2, 3, 4, 5]");
  ASSERT_TRUE(value->IsArray());
  EXPECT_EQ(5u, Array::Cast(*value)->Length());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Array.prototype");
  ExpectScriptTrue("result.toString() === '1,2,3,4,5'");

926
  // A long (sparse) array.
927 928 929 930 931
  value = RoundTripTest("var x = new Array(1000); x[500] = 42; x;");
  ASSERT_TRUE(value->IsArray());
  EXPECT_EQ(1000u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[500] === 42");

932
  // Duplicate reference.
933 934 935 936 937
  value = RoundTripTest("var y = {}; [y, y];");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(2u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[0] === result[1]");

938
  // Duplicate reference in a sparse array.
939 940 941 942 943 944
  value = RoundTripTest("var x = new Array(1000); x[1] = x[500] = {}; x;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(1000u, Array::Cast(*value)->Length());
  ExpectScriptTrue("typeof result[1] === 'object'");
  ExpectScriptTrue("result[1] === result[500]");

945
  // Self reference.
946 947 948 949 950
  value = RoundTripTest("var y = []; y[0] = y; y;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(1u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[0] === result");

951
  // Self reference in a sparse array.
952 953 954 955 956
  value = RoundTripTest("var y = new Array(1000); y[519] = y; y;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(1000u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[519] === result");

957
  // Array with additional properties.
958 959 960 961 962 963
  value = RoundTripTest("var y = [1, 2]; y.foo = 'bar'; y;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(2u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result.toString() === '1,2'");
  ExpectScriptTrue("result.foo === 'bar'");

964
  // Sparse array with additional properties.
965 966 967 968 969 970
  value = RoundTripTest("var y = new Array(1000); y.foo = 'bar'; y;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(1000u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result.toString() === ','.repeat(999)");
  ExpectScriptTrue("result.foo === 'bar'");

971
  // The distinction between holes and undefined elements must be maintained.
972 973 974 975 976 977 978
  value = RoundTripTest("[,undefined]");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(2u, Array::Cast(*value)->Length());
  ExpectScriptTrue("typeof result[0] === 'undefined'");
  ExpectScriptTrue("typeof result[1] === 'undefined'");
  ExpectScriptTrue("!result.hasOwnProperty(0)");
  ExpectScriptTrue("result.hasOwnProperty(1)");
979 980 981 982
}

TEST_F(ValueSerializerTest, DecodeArray) {
  // A simple array of integers.
983 984 985 986 987 988 989 990 991
  Local<Value> value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x41, 0x05, 0x3F, 0x01, 0x49, 0x02,
                  0x3F, 0x01, 0x49, 0x04, 0x3F, 0x01, 0x49, 0x06, 0x3F, 0x01,
                  0x49, 0x08, 0x3F, 0x01, 0x49, 0x0A, 0x24, 0x00, 0x05, 0x00});
  ASSERT_TRUE(value->IsArray());
  EXPECT_EQ(5u, Array::Cast(*value)->Length());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Array.prototype");
  ExpectScriptTrue("result.toString() === '1,2,3,4,5'");

992
  // A long (sparse) array.
993 994 995 996 997 998 999
  value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x61, 0xE8, 0x07, 0x3F, 0x01, 0x49,
                  0xE8, 0x07, 0x3F, 0x01, 0x49, 0x54, 0x40, 0x01, 0xE8, 0x07});
  ASSERT_TRUE(value->IsArray());
  EXPECT_EQ(1000u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[500] === 42");

1000
  // Duplicate reference.
1001 1002 1003 1004 1005 1006
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x41, 0x02, 0x3F, 0x01, 0x6F,
                      0x7B, 0x00, 0x3F, 0x02, 0x5E, 0x01, 0x24, 0x00, 0x02});
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(2u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[0] === result[1]");

1007
  // Duplicate reference in a sparse array.
1008 1009 1010 1011 1012 1013 1014 1015 1016
  value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x61, 0xE8, 0x07, 0x3F, 0x01, 0x49,
                  0x02, 0x3F, 0x01, 0x6F, 0x7B, 0x00, 0x3F, 0x02, 0x49, 0xE8,
                  0x07, 0x3F, 0x02, 0x5E, 0x01, 0x40, 0x02, 0xE8, 0x07, 0x00});
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(1000u, Array::Cast(*value)->Length());
  ExpectScriptTrue("typeof result[1] === 'object'");
  ExpectScriptTrue("result[1] === result[500]");

1017
  // Self reference.
1018 1019 1020 1021 1022 1023
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x41, 0x01, 0x3F, 0x01, 0x5E,
                      0x00, 0x24, 0x00, 0x01, 0x00});
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(1u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[0] === result");

1024
  // Self reference in a sparse array.
1025 1026 1027 1028 1029 1030 1031
  value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x61, 0xE8, 0x07, 0x3F, 0x01, 0x49,
                  0x8E, 0x08, 0x3F, 0x01, 0x5E, 0x00, 0x40, 0x01, 0xE8, 0x07});
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(1000u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[519] === result");

1032
  // Array with additional properties.
1033 1034 1035 1036 1037 1038 1039 1040 1041
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x41, 0x02, 0x3F, 0x01,
                      0x49, 0x02, 0x3F, 0x01, 0x49, 0x04, 0x3F, 0x01,
                      0x53, 0x03, 0x66, 0x6F, 0x6F, 0x3F, 0x01, 0x53,
                      0x03, 0x62, 0x61, 0x72, 0x24, 0x01, 0x02, 0x00});
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(2u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result.toString() === '1,2'");
  ExpectScriptTrue("result.foo === 'bar'");

1042
  // Sparse array with additional properties.
1043 1044 1045 1046 1047 1048 1049 1050
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x61, 0xE8, 0x07, 0x3F, 0x01,
                      0x53, 0x03, 0x66, 0x6F, 0x6F, 0x3F, 0x01, 0x53, 0x03,
                      0x62, 0x61, 0x72, 0x40, 0x01, 0xE8, 0x07, 0x00});
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(1000u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result.toString() === ','.repeat(999)");
  ExpectScriptTrue("result.foo === 'bar'");

1051 1052 1053
  // The distinction between holes and undefined elements must be maintained.
  // Note that since the previous output from Chrome fails this test, an
  // encoding using the sparse format was constructed instead.
1054 1055 1056 1057 1058 1059 1060 1061
  value =
      DecodeTest({0xFF, 0x09, 0x61, 0x02, 0x49, 0x02, 0x5F, 0x40, 0x01, 0x02});
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(2u, Array::Cast(*value)->Length());
  ExpectScriptTrue("typeof result[0] === 'undefined'");
  ExpectScriptTrue("typeof result[1] === 'undefined'");
  ExpectScriptTrue("!result.hasOwnProperty(0)");
  ExpectScriptTrue("result.hasOwnProperty(1)");
1062 1063
}

1064 1065 1066
TEST_F(ValueSerializerTest, DecodeInvalidOverLargeArray) {
  // So large it couldn't exist in the V8 heap, and its size couldn't fit in a
  // SMI on 32-bit systems (2^30).
1067
  InvalidDecodeTest({0xFF, 0x09, 0x41, 0x80, 0x80, 0x80, 0x80, 0x04});
1068
  // Not so large, but there isn't enough data left in the buffer.
1069
  InvalidDecodeTest({0xFF, 0x09, 0x41, 0x01});
1070 1071
}

1072 1073 1074 1075
TEST_F(ValueSerializerTest, RoundTripArrayWithNonEnumerableElement) {
  // Even though this array looks like [1,5,3], the 5 should be missing from the
  // perspective of structured clone, which only clones properties that were
  // enumerable.
1076 1077 1078 1079 1080 1081 1082
  Local<Value> value = RoundTripTest(
      "var x = [1,2,3];"
      "Object.defineProperty(x, '1', {enumerable:false, value:5});"
      "x;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(3u, Array::Cast(*value)->Length());
  ExpectScriptTrue("!result.hasOwnProperty('1')");
1083 1084 1085 1086
}

TEST_F(ValueSerializerTest, RoundTripArrayWithTrickyGetters) {
  // If an element is deleted before it is serialized, then it's deleted.
1087 1088 1089 1090 1091 1092 1093
  Local<Value> value =
      RoundTripTest("var x = [{ get a() { delete x[1]; }}, 42]; x;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(2u, Array::Cast(*value)->Length());
  ExpectScriptTrue("typeof result[1] === 'undefined'");
  ExpectScriptTrue("!result.hasOwnProperty(1)");

1094
  // Same for sparse arrays.
1095 1096 1097 1098 1099 1100 1101 1102 1103
  value = RoundTripTest(
      "var x = [{ get a() { delete x[1]; }}, 42];"
      "x.length = 1000;"
      "x;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(1000u, Array::Cast(*value)->Length());
  ExpectScriptTrue("typeof result[1] === 'undefined'");
  ExpectScriptTrue("!result.hasOwnProperty(1)");

1104 1105
  // If the length is changed, then the resulting array still has the original
  // length, but elements that were not yet serialized are gone.
1106 1107 1108 1109 1110 1111
  value = RoundTripTest("var x = [1, { get a() { x.length = 0; }}, 3, 4]; x;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(4u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[0] === 1");
  ExpectScriptTrue("!result.hasOwnProperty(2)");

1112 1113
  // The same is true if the length is shortened, but there are still items
  // remaining.
1114 1115 1116 1117 1118 1119
  value = RoundTripTest("var x = [1, { get a() { x.length = 3; }}, 3, 4]; x;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(4u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[2] === 3");
  ExpectScriptTrue("!result.hasOwnProperty(3)");

1120
  // Same for sparse arrays.
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
  value = RoundTripTest(
      "var x = [1, { get a() { x.length = 0; }}, 3, 4];"
      "x.length = 1000;"
      "x;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(1000u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[0] === 1");
  ExpectScriptTrue("!result.hasOwnProperty(2)");

  value = RoundTripTest(
      "var x = [1, { get a() { x.length = 3; }}, 3, 4];"
      "x.length = 1000;"
      "x;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(1000u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[2] === 3");
  ExpectScriptTrue("!result.hasOwnProperty(3)");

1139 1140
  // If a getter makes a property non-enumerable, it should still be enumerated
  // as enumeration happens once before getters are invoked.
1141 1142 1143 1144 1145 1146 1147 1148 1149
  value = RoundTripTest(
      "var x = [{ get a() {"
      "  Object.defineProperty(x, '1', { value: 3, enumerable: false });"
      "}}, 2];"
      "x;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(2u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[1] === 3");

1150
  // Same for sparse arrays.
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160
  value = RoundTripTest(
      "var x = [{ get a() {"
      "  Object.defineProperty(x, '1', { value: 3, enumerable: false });"
      "}}, 2];"
      "x.length = 1000;"
      "x;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(1000u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[1] === 3");

1161
  // Getters on the array itself must also run.
1162 1163 1164 1165 1166 1167 1168 1169
  value = RoundTripTest(
      "var x = [1, 2, 3];"
      "Object.defineProperty(x, '1', { enumerable: true, get: () => 4 });"
      "x;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(3u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[1] === 4");

1170
  // Same for sparse arrays.
1171 1172 1173 1174 1175 1176 1177 1178 1179
  value = RoundTripTest(
      "var x = [1, 2, 3];"
      "Object.defineProperty(x, '1', { enumerable: true, get: () => 4 });"
      "x.length = 1000;"
      "x;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(1000u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result[1] === 4");

1180
  // Even with a getter that deletes things, we don't read from the prototype.
1181 1182 1183 1184 1185 1186 1187 1188
  value = RoundTripTest(
      "var x = [{ get a() { delete x[1]; } }, 2];"
      "x.__proto__ = Object.create(Array.prototype, { 1: { value: 6 } });"
      "x;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(2u, Array::Cast(*value)->Length());
  ExpectScriptTrue("!(1 in result)");

1189
  // Same for sparse arrays.
1190 1191 1192 1193 1194 1195 1196 1197
  value = RoundTripTest(
      "var x = [{ get a() { delete x[1]; } }, 2];"
      "x.__proto__ = Object.create(Array.prototype, { 1: { value: 6 } });"
      "x.length = 1000;"
      "x;");
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(1000u, Array::Cast(*value)->Length());
  ExpectScriptTrue("!(1 in result)");
1198 1199
}

1200 1201
TEST_F(ValueSerializerTest, DecodeSparseArrayVersion0) {
  // Empty (sparse) array.
1202 1203 1204 1205
  Local<Value> value = DecodeTestForVersion0({0x40, 0x00, 0x00, 0x00});
  ASSERT_TRUE(value->IsArray());
  ASSERT_EQ(0u, Array::Cast(*value)->Length());

1206
  // Sparse array with a mixture of elements and properties.
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
  value = DecodeTestForVersion0({0x55, 0x00, 0x53, 0x01, 'a',  0x55, 0x02, 0x55,
                                 0x05, 0x53, 0x03, 'f',  'o',  'o',  0x53, 0x03,
                                 'b',  'a',  'r',  0x53, 0x03, 'b',  'a',  'z',
                                 0x49, 0x0B, 0x40, 0x04, 0x03, 0x00});
  ASSERT_TRUE(value->IsArray());
  EXPECT_EQ(3u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result.toString() === 'a,,5'");
  ExpectScriptTrue("!(1 in result)");
  ExpectScriptTrue("result.foo === 'bar'");
  ExpectScriptTrue("result.baz === -6");

1218
  // Sparse array in a sparse array (sanity check of nesting).
1219 1220 1221 1222 1223 1224 1225 1226
  value = DecodeTestForVersion0(
      {0x55, 0x01, 0x55, 0x01, 0x54, 0x40, 0x01, 0x02, 0x40, 0x01, 0x02, 0x00});
  ASSERT_TRUE(value->IsArray());
  EXPECT_EQ(2u, Array::Cast(*value)->Length());
  ExpectScriptTrue("!(0 in result)");
  ExpectScriptTrue("result[1] instanceof Array");
  ExpectScriptTrue("!(0 in result[1])");
  ExpectScriptTrue("result[1][1] === true");
1227 1228
}

1229 1230 1231
TEST_F(ValueSerializerTest, RoundTripDenseArrayContainingUndefined) {
  // In previous serialization versions, this would be interpreted as an absent
  // property.
1232 1233 1234 1235 1236
  Local<Value> value = RoundTripTest("[undefined]");
  ASSERT_TRUE(value->IsArray());
  EXPECT_EQ(1u, Array::Cast(*value)->Length());
  ExpectScriptTrue("result.hasOwnProperty(0)");
  ExpectScriptTrue("result[0] === undefined");
1237 1238 1239 1240 1241
}

TEST_F(ValueSerializerTest, DecodeDenseArrayContainingUndefined) {
  // In previous versions, "undefined" in a dense array signified absence of the
  // element (for compatibility). In new versions, it has a separate encoding.
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
  Local<Value> value =
      DecodeTest({0xFF, 0x09, 0x41, 0x01, 0x5F, 0x24, 0x00, 0x01});
  ExpectScriptTrue("!(0 in result)");

  value = DecodeTest({0xFF, 0x0B, 0x41, 0x01, 0x5F, 0x24, 0x00, 0x01});
  ExpectScriptTrue("0 in result");
  ExpectScriptTrue("result[0] === undefined");

  value = DecodeTest({0xFF, 0x0B, 0x41, 0x01, 0x2D, 0x24, 0x00, 0x01});
  ExpectScriptTrue("!(0 in result)");
1252 1253
}

1254
TEST_F(ValueSerializerTest, RoundTripDate) {
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
  Local<Value> value = RoundTripTest("new Date(1e6)");
  ASSERT_TRUE(value->IsDate());
  EXPECT_EQ(1e6, Date::Cast(*value)->ValueOf());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Date.prototype");

  value = RoundTripTest("new Date(Date.UTC(1867, 6, 1))");
  ASSERT_TRUE(value->IsDate());
  ExpectScriptTrue("result.toISOString() === '1867-07-01T00:00:00.000Z'");

  value = RoundTripTest("new Date(NaN)");
  ASSERT_TRUE(value->IsDate());
  EXPECT_TRUE(std::isnan(Date::Cast(*value)->ValueOf()));

  value = RoundTripTest("({ a: new Date(), get b() { return this.a; } })");
  ExpectScriptTrue("result.a instanceof Date");
  ExpectScriptTrue("result.a === result.b");
1271 1272 1273
}

TEST_F(ValueSerializerTest, DecodeDate) {
1274
  Local<Value> value;
1275
#if defined(V8_TARGET_LITTLE_ENDIAN)
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00,
                      0x80, 0x84, 0x2E, 0x41, 0x00});
  ASSERT_TRUE(value->IsDate());
  EXPECT_EQ(1e6, Date::Cast(*value)->ValueOf());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Date.prototype");

  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x44, 0x00, 0x00, 0x20, 0x45,
                      0x27, 0x89, 0x87, 0xC2, 0x00});
  ASSERT_TRUE(value->IsDate());
  ExpectScriptTrue("result.toISOString() === '1867-07-01T00:00:00.000Z'");

  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00,
                      0x00, 0x00, 0xF8, 0x7F, 0x00});
  ASSERT_TRUE(value->IsDate());
  EXPECT_TRUE(std::isnan(Date::Cast(*value)->ValueOf()));
1291
#else
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x44, 0x41, 0x2E, 0x84, 0x80,
                      0x00, 0x00, 0x00, 0x00, 0x00});
  ASSERT_TRUE(value->IsDate());
  EXPECT_EQ(1e6, Date::Cast(*value)->ValueOf());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Date.prototype");

  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x44, 0xC2, 0x87, 0x89, 0x27,
                      0x45, 0x20, 0x00, 0x00, 0x00});
  ASSERT_TRUE(value->IsDate());
  ExpectScriptTrue("result.toISOString() === '1867-07-01T00:00:00.000Z'");

  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x44, 0x7F, 0xF8, 0x00, 0x00,
                      0x00, 0x00, 0x00, 0x00, 0x00});
  ASSERT_TRUE(value->IsDate());
  EXPECT_TRUE(std::isnan(Date::Cast(*value)->ValueOf()));
1307
#endif
1308 1309 1310 1311 1312 1313
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x53,
                      0x01, 0x61, 0x3F, 0x01, 0x44, 0x00, 0x20, 0x39,
                      0x50, 0x37, 0x6A, 0x75, 0x42, 0x3F, 0x02, 0x53,
                      0x01, 0x62, 0x3F, 0x02, 0x5E, 0x01, 0x7B, 0x02});
  ExpectScriptTrue("result.a instanceof Date");
  ExpectScriptTrue("result.a === result.b");
1314 1315
}

1316
TEST_F(ValueSerializerTest, RoundTripValueObjects) {
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
  Local<Value> value = RoundTripTest("new Boolean(true)");
  ExpectScriptTrue("Object.getPrototypeOf(result) === Boolean.prototype");
  ExpectScriptTrue("result.valueOf() === true");

  value = RoundTripTest("new Boolean(false)");
  ExpectScriptTrue("Object.getPrototypeOf(result) === Boolean.prototype");
  ExpectScriptTrue("result.valueOf() === false");

  value =
      RoundTripTest("({ a: new Boolean(true), get b() { return this.a; }})");
  ExpectScriptTrue("result.a instanceof Boolean");
  ExpectScriptTrue("result.a === result.b");

  value = RoundTripTest("new Number(-42)");
  ExpectScriptTrue("Object.getPrototypeOf(result) === Number.prototype");
  ExpectScriptTrue("result.valueOf() === -42");

  value = RoundTripTest("new Number(NaN)");
  ExpectScriptTrue("Object.getPrototypeOf(result) === Number.prototype");
  ExpectScriptTrue("Number.isNaN(result.valueOf())");

  value = RoundTripTest("({ a: new Number(6), get b() { return this.a; }})");
  ExpectScriptTrue("result.a instanceof Number");
  ExpectScriptTrue("result.a === result.b");

  value = RoundTripTest("new String('Qu\\xe9bec')");
  ExpectScriptTrue("Object.getPrototypeOf(result) === String.prototype");
  ExpectScriptTrue("result.valueOf() === 'Qu\\xe9bec'");
  ExpectScriptTrue("result.length === 6");

  value = RoundTripTest("new String('\\ud83d\\udc4a')");
  ExpectScriptTrue("Object.getPrototypeOf(result) === String.prototype");
  ExpectScriptTrue("result.valueOf() === '\\ud83d\\udc4a'");
  ExpectScriptTrue("result.length === 2");

  value = RoundTripTest("({ a: new String(), get b() { return this.a; }})");
  ExpectScriptTrue("result.a instanceof String");
  ExpectScriptTrue("result.a === result.b");
1355 1356 1357 1358 1359 1360 1361 1362
}

TEST_F(ValueSerializerTest, RejectsOtherValueObjects) {
  // This is a roundabout way of getting an instance of Symbol.
  InvalidEncodeTest("Object.valueOf.apply(Symbol())");
}

TEST_F(ValueSerializerTest, DecodeValueObjects) {
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
  Local<Value> value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x79, 0x00});
  ExpectScriptTrue("Object.getPrototypeOf(result) === Boolean.prototype");
  ExpectScriptTrue("result.valueOf() === true");

  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x78, 0x00});
  ExpectScriptTrue("Object.getPrototypeOf(result) === Boolean.prototype");
  ExpectScriptTrue("result.valueOf() === false");

  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x53,
                      0x01, 0x61, 0x3F, 0x01, 0x79, 0x3F, 0x02, 0x53,
                      0x01, 0x62, 0x3F, 0x02, 0x5E, 0x01, 0x7B, 0x02});
  ExpectScriptTrue("result.a instanceof Boolean");
  ExpectScriptTrue("result.a === result.b");

1377
#if defined(V8_TARGET_LITTLE_ENDIAN)
1378 1379 1380 1381 1382 1383 1384 1385 1386
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x6E, 0x00, 0x00, 0x00, 0x00,
                      0x00, 0x00, 0x45, 0xC0, 0x00});
  ExpectScriptTrue("Object.getPrototypeOf(result) === Number.prototype");
  ExpectScriptTrue("result.valueOf() === -42");

  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x6E, 0x00, 0x00, 0x00, 0x00,
                      0x00, 0x00, 0xF8, 0x7F, 0x00});
  ExpectScriptTrue("Object.getPrototypeOf(result) === Number.prototype");
  ExpectScriptTrue("Number.isNaN(result.valueOf())");
1387
#else
1388 1389 1390 1391 1392 1393 1394 1395 1396
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x6E, 0xC0, 0x45, 0x00, 0x00,
                      0x00, 0x00, 0x00, 0x00, 0x00});
  ExpectScriptTrue("Object.getPrototypeOf(result) === Number.prototype");
  ExpectScriptTrue("result.valueOf() === -42");

  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x6E, 0x7F, 0xF8, 0x00, 0x00,
                      0x00, 0x00, 0x00, 0x00, 0x00});
  ExpectScriptTrue("Object.getPrototypeOf(result) === Number.prototype");
  ExpectScriptTrue("Number.isNaN(result.valueOf())");
1397
#endif
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x53,
                      0x01, 0x61, 0x3F, 0x01, 0x6E, 0x00, 0x00, 0x00,
                      0x00, 0x00, 0x00, 0x18, 0x40, 0x3F, 0x02, 0x53,
                      0x01, 0x62, 0x3F, 0x02, 0x5E, 0x01, 0x7B, 0x02});
  ExpectScriptTrue("result.a instanceof Number");
  ExpectScriptTrue("result.a === result.b");

  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x73, 0x07, 0x51, 0x75, 0xC3,
                      0xA9, 0x62, 0x65, 0x63, 0x00});
  ExpectScriptTrue("Object.getPrototypeOf(result) === String.prototype");
  ExpectScriptTrue("result.valueOf() === 'Qu\\xe9bec'");
  ExpectScriptTrue("result.length === 6");

  value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x73, 0x04, 0xF0, 0x9F, 0x91, 0x8A});
  ExpectScriptTrue("Object.getPrototypeOf(result) === String.prototype");
  ExpectScriptTrue("result.valueOf() === '\\ud83d\\udc4a'");
  ExpectScriptTrue("result.length === 2");

  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x53, 0x01,
                      0x61, 0x3F, 0x01, 0x73, 0x00, 0x3F, 0x02, 0x53, 0x01,
                      0x62, 0x3F, 0x02, 0x5E, 0x01, 0x7B, 0x02, 0x00});
  ExpectScriptTrue("result.a instanceof String");
  ExpectScriptTrue("result.a === result.b");
1422 1423

  // String object containing a Latin-1 string.
1424 1425 1426 1427 1428
  value =
      DecodeTest({0xFF, 0x0C, 0x73, 0x22, 0x06, 'Q', 'u', 0xE9, 'b', 'e', 'c'});
  ExpectScriptTrue("Object.getPrototypeOf(result) === String.prototype");
  ExpectScriptTrue("result.valueOf() === 'Qu\\xe9bec'");
  ExpectScriptTrue("result.length === 6");
1429 1430
}

1431
TEST_F(ValueSerializerTest, RoundTripRegExp) {
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
  Local<Value> value = RoundTripTest("/foo/g");
  ASSERT_TRUE(value->IsRegExp());
  ExpectScriptTrue("Object.getPrototypeOf(result) === RegExp.prototype");
  ExpectScriptTrue("result.toString() === '/foo/g'");

  value = RoundTripTest("new RegExp('Qu\\xe9bec', 'i')");
  ASSERT_TRUE(value->IsRegExp());
  ExpectScriptTrue("result.toString() === '/Qu\\xe9bec/i'");

  value = RoundTripTest("new RegExp('\\ud83d\\udc4a', 'ug')");
  ASSERT_TRUE(value->IsRegExp());
  ExpectScriptTrue("result.toString() === '/\\ud83d\\udc4a/gu'");

  value = RoundTripTest("({ a: /foo/gi, get b() { return this.a; }})");
  ExpectScriptTrue("result.a instanceof RegExp");
  ExpectScriptTrue("result.a === result.b");
1448 1449 1450
}

TEST_F(ValueSerializerTest, DecodeRegExp) {
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
  Local<Value> value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x52, 0x03, 0x66, 0x6F, 0x6F, 0x01});
  ASSERT_TRUE(value->IsRegExp());
  ExpectScriptTrue("Object.getPrototypeOf(result) === RegExp.prototype");
  ExpectScriptTrue("result.toString() === '/foo/g'");

  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x52, 0x07, 0x51, 0x75, 0xC3,
                      0xA9, 0x62, 0x65, 0x63, 0x02});
  ASSERT_TRUE(value->IsRegExp());
  ExpectScriptTrue("result.toString() === '/Qu\\xe9bec/i'");

  value = DecodeTest(
      {0xFF, 0x09, 0x3F, 0x00, 0x52, 0x04, 0xF0, 0x9F, 0x91, 0x8A, 0x11, 0x00});
  ASSERT_TRUE(value->IsRegExp());
  ExpectScriptTrue("result.toString() === '/\\ud83d\\udc4a/gu'");

  value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x53, 0x01, 0x61,
                  0x3F, 0x01, 0x52, 0x03, 0x66, 0x6F, 0x6F, 0x03, 0x3F, 0x02,
                  0x53, 0x01, 0x62, 0x3F, 0x02, 0x5E, 0x01, 0x7B, 0x02, 0x00});
  ExpectScriptTrue("result.a instanceof RegExp");
  ExpectScriptTrue("result.a === result.b");
1473 1474

  // RegExp containing a Latin-1 string.
1475 1476 1477 1478
  value = DecodeTest(
      {0xFF, 0x0C, 0x52, 0x22, 0x06, 'Q', 'u', 0xE9, 'b', 'e', 'c', 0x02});
  ASSERT_TRUE(value->IsRegExp());
  ExpectScriptTrue("result.toString() === '/Qu\\xe9bec/i'");
1479 1480
}

1481
// Tests that invalid flags are not accepted by the deserializer.
1482
TEST_F(ValueSerializerTest, DecodeRegExpDotAll) {
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
  Local<Value> value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x52, 0x03, 0x66, 0x6F, 0x6F, 0x1F});
  ASSERT_TRUE(value->IsRegExp());
  ExpectScriptTrue("Object.getPrototypeOf(result) === RegExp.prototype");
  ExpectScriptTrue("result.toString() === '/foo/gimuy'");

  value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x52, 0x03, 0x66, 0x6F, 0x6F, 0x3F});
  ASSERT_TRUE(value->IsRegExp());
  ExpectScriptTrue("Object.getPrototypeOf(result) === RegExp.prototype");
  ExpectScriptTrue("result.toString() === '/foo/gimsuy'");

1495
  InvalidDecodeTest(
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
      {0xFF, 0x09, 0x3F, 0x00, 0x52, 0x03, 0x66, 0x6F, 0x6F, 0xFF});
}

TEST_F(ValueSerializerTest, DecodeLinearRegExp) {
  bool flag_was_enabled = i::FLAG_enable_experimental_regexp_engine;

  // The last byte encodes the regexp flags.
  std::vector<uint8_t> regexp_encoding = {0xFF, 0x09, 0x3F, 0x00, 0x52,
                                          0x03, 0x66, 0x6F, 0x6F, 0x6D};

  i::FLAG_enable_experimental_regexp_engine = true;
  Local<Value> value = DecodeTest(regexp_encoding);
  ASSERT_TRUE(value->IsRegExp());
  ExpectScriptTrue("Object.getPrototypeOf(result) === RegExp.prototype");
  ExpectScriptTrue("result.toString() === '/foo/glmsy'");

  i::FLAG_enable_experimental_regexp_engine = false;
  InvalidDecodeTest(regexp_encoding);

  i::FLAG_enable_experimental_regexp_engine = flag_was_enabled;
1516 1517
}

1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
TEST_F(ValueSerializerTest, DecodeHasIndicesRegExp) {
  bool flag_was_enabled = i::FLAG_harmony_regexp_match_indices;

  // The last byte encodes the regexp flags.
  std::vector<uint8_t> regexp_encoding = {0xFF, 0x09, 0x3F, 0x00, 0x52, 0x03,
                                          0x66, 0x6F, 0x6F, 0xAD, 0x01};

  i::FLAG_harmony_regexp_match_indices = true;
  Local<Value> value = DecodeTest(regexp_encoding);
  ASSERT_TRUE(value->IsRegExp());
  ExpectScriptTrue("Object.getPrototypeOf(result) === RegExp.prototype");
  ExpectScriptTrue("result.toString() === '/foo/dgmsy'");

  i::FLAG_harmony_regexp_match_indices = false;
  InvalidDecodeTest(regexp_encoding);

  i::FLAG_harmony_regexp_match_indices = flag_was_enabled;
}

1537
TEST_F(ValueSerializerTest, RoundTripMap) {
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
  Local<Value> value = RoundTripTest("var m = new Map(); m.set(42, 'foo'); m;");
  ASSERT_TRUE(value->IsMap());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Map.prototype");
  ExpectScriptTrue("result.size === 1");
  ExpectScriptTrue("result.get(42) === 'foo'");

  value = RoundTripTest("var m = new Map(); m.set(m, m); m;");
  ASSERT_TRUE(value->IsMap());
  ExpectScriptTrue("result.size === 1");
  ExpectScriptTrue("result.get(result) === result");

1549
  // Iteration order must be preserved.
1550 1551 1552 1553 1554 1555
  value = RoundTripTest(
      "var m = new Map();"
      "m.set(1, 0); m.set('a', 0); m.set(3, 0); m.set(2, 0);"
      "m;");
  ASSERT_TRUE(value->IsMap());
  ExpectScriptTrue("Array.from(result.keys()).toString() === '1,a,3,2'");
1556 1557 1558
}

TEST_F(ValueSerializerTest, DecodeMap) {
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
  Local<Value> value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x3B, 0x3F, 0x01, 0x49, 0x54, 0x3F,
                  0x01, 0x53, 0x03, 0x66, 0x6F, 0x6F, 0x3A, 0x02});
  ASSERT_TRUE(value->IsMap());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Map.prototype");
  ExpectScriptTrue("result.size === 1");
  ExpectScriptTrue("result.get(42) === 'foo'");

  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x3B, 0x3F, 0x01, 0x5E, 0x00,
                      0x3F, 0x01, 0x5E, 0x00, 0x3A, 0x02, 0x00});
  ASSERT_TRUE(value->IsMap());
  ExpectScriptTrue("result.size === 1");
  ExpectScriptTrue("result.get(result) === result");

1573
  // Iteration order must be preserved.
1574 1575 1576 1577 1578 1579 1580
  value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x3B, 0x3F, 0x01, 0x49, 0x02, 0x3F,
                  0x01, 0x49, 0x00, 0x3F, 0x01, 0x53, 0x01, 0x61, 0x3F, 0x01,
                  0x49, 0x00, 0x3F, 0x01, 0x49, 0x06, 0x3F, 0x01, 0x49, 0x00,
                  0x3F, 0x01, 0x49, 0x04, 0x3F, 0x01, 0x49, 0x00, 0x3A, 0x08});
  ASSERT_TRUE(value->IsMap());
  ExpectScriptTrue("Array.from(result.keys()).toString() === '1,a,3,2'");
1581 1582 1583 1584 1585
}

TEST_F(ValueSerializerTest, RoundTripMapWithTrickyGetters) {
  // Even if an entry is removed or reassigned, the original key/value pair is
  // used.
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
  Local<Value> value = RoundTripTest(
      "var m = new Map();"
      "m.set(0, { get a() {"
      "  m.delete(1); m.set(2, 'baz'); m.set(3, 'quux');"
      "}});"
      "m.set(1, 'foo');"
      "m.set(2, 'bar');"
      "m;");
  ASSERT_TRUE(value->IsMap());
  ExpectScriptTrue("Array.from(result.keys()).toString() === '0,1,2'");
  ExpectScriptTrue("result.get(1) === 'foo'");
  ExpectScriptTrue("result.get(2) === 'bar'");

1599
  // However, deeper modifications of objects yet to be serialized still apply.
1600 1601 1602 1603 1604 1605 1606 1607 1608
  value = RoundTripTest(
      "var m = new Map();"
      "var key = { get a() { value.foo = 'bar'; } };"
      "var value = { get a() { key.baz = 'quux'; } };"
      "m.set(key, value);"
      "m;");
  ASSERT_TRUE(value->IsMap());
  ExpectScriptTrue("!('baz' in Array.from(result.keys())[0])");
  ExpectScriptTrue("Array.from(result.values())[0].foo === 'bar'");
1609 1610 1611
}

TEST_F(ValueSerializerTest, RoundTripSet) {
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
  Local<Value> value =
      RoundTripTest("var s = new Set(); s.add(42); s.add('foo'); s;");
  ASSERT_TRUE(value->IsSet());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Set.prototype");
  ExpectScriptTrue("result.size === 2");
  ExpectScriptTrue("result.has(42)");
  ExpectScriptTrue("result.has('foo')");

  value = RoundTripTest("var s = new Set(); s.add(s); s;");
  ASSERT_TRUE(value->IsSet());
  ExpectScriptTrue("result.size === 1");
  ExpectScriptTrue("result.has(result)");

1625
  // Iteration order must be preserved.
1626 1627 1628 1629 1630 1631
  value = RoundTripTest(
      "var s = new Set();"
      "s.add(1); s.add('a'); s.add(3); s.add(2);"
      "s;");
  ASSERT_TRUE(value->IsSet());
  ExpectScriptTrue("Array.from(result.keys()).toString() === '1,a,3,2'");
1632 1633 1634
}

TEST_F(ValueSerializerTest, DecodeSet) {
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
  Local<Value> value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x27, 0x3F, 0x01, 0x49, 0x54, 0x3F,
                  0x01, 0x53, 0x03, 0x66, 0x6F, 0x6F, 0x2C, 0x02});
  ASSERT_TRUE(value->IsSet());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Set.prototype");
  ExpectScriptTrue("result.size === 2");
  ExpectScriptTrue("result.has(42)");
  ExpectScriptTrue("result.has('foo')");

  value = DecodeTest(
      {0xFF, 0x09, 0x3F, 0x00, 0x27, 0x3F, 0x01, 0x5E, 0x00, 0x2C, 0x01, 0x00});
  ASSERT_TRUE(value->IsSet());
  ExpectScriptTrue("result.size === 1");
  ExpectScriptTrue("result.has(result)");

1650
  // Iteration order must be preserved.
1651 1652 1653 1654 1655
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x27, 0x3F, 0x01, 0x49,
                      0x02, 0x3F, 0x01, 0x53, 0x01, 0x61, 0x3F, 0x01,
                      0x49, 0x06, 0x3F, 0x01, 0x49, 0x04, 0x2C, 0x04});
  ASSERT_TRUE(value->IsSet());
  ExpectScriptTrue("Array.from(result.keys()).toString() === '1,a,3,2'");
1656 1657 1658 1659 1660
}

TEST_F(ValueSerializerTest, RoundTripSetWithTrickyGetters) {
  // Even if an element is added or removed during serialization, the original
  // set of elements is used.
1661 1662 1663 1664 1665 1666 1667 1668 1669
  Local<Value> value = RoundTripTest(
      "var s = new Set();"
      "s.add({ get a() { s.delete(1); s.add(2); } });"
      "s.add(1);"
      "s;");
  ASSERT_TRUE(value->IsSet());
  ExpectScriptTrue(
      "Array.from(result.keys()).toString() === '[object Object],1'");

1670
  // However, deeper modifications of objects yet to be serialized still apply.
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
  value = RoundTripTest(
      "var s = new Set();"
      "var first = { get a() { second.foo = 'bar'; } };"
      "var second = { get a() { first.baz = 'quux'; } };"
      "s.add(first);"
      "s.add(second);"
      "s;");
  ASSERT_TRUE(value->IsSet());
  ExpectScriptTrue("!('baz' in Array.from(result.keys())[0])");
  ExpectScriptTrue("Array.from(result.keys())[1].foo === 'bar'");
1681 1682
}

1683
TEST_F(ValueSerializerTest, RoundTripArrayBuffer) {
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
  Local<Value> value = RoundTripTest("new ArrayBuffer()");
  ASSERT_TRUE(value->IsArrayBuffer());
  EXPECT_EQ(0u, ArrayBuffer::Cast(*value)->ByteLength());
  ExpectScriptTrue("Object.getPrototypeOf(result) === ArrayBuffer.prototype");

  value = RoundTripTest("new Uint8Array([0, 128, 255]).buffer");
  ASSERT_TRUE(value->IsArrayBuffer());
  EXPECT_EQ(3u, ArrayBuffer::Cast(*value)->ByteLength());
  ExpectScriptTrue("new Uint8Array(result).toString() === '0,128,255'");

  value =
      RoundTripTest("({ a: new ArrayBuffer(), get b() { return this.a; }})");
  ExpectScriptTrue("result.a instanceof ArrayBuffer");
  ExpectScriptTrue("result.a === result.b");
1698 1699 1700
}

TEST_F(ValueSerializerTest, DecodeArrayBuffer) {
1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
  Local<Value> value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x42, 0x00});
  ASSERT_TRUE(value->IsArrayBuffer());
  EXPECT_EQ(0u, ArrayBuffer::Cast(*value)->ByteLength());
  ExpectScriptTrue("Object.getPrototypeOf(result) === ArrayBuffer.prototype");

  value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x42, 0x03, 0x00, 0x80, 0xFF, 0x00});
  ASSERT_TRUE(value->IsArrayBuffer());
  EXPECT_EQ(3u, ArrayBuffer::Cast(*value)->ByteLength());
  ExpectScriptTrue("new Uint8Array(result).toString() === '0,128,255'");

  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x53, 0x01,
                      0x61, 0x3F, 0x01, 0x42, 0x00, 0x3F, 0x02, 0x53, 0x01,
                      0x62, 0x3F, 0x02, 0x5E, 0x01, 0x7B, 0x02, 0x00});
  ExpectScriptTrue("result.a instanceof ArrayBuffer");
  ExpectScriptTrue("result.a === result.b");
1717 1718 1719
}

TEST_F(ValueSerializerTest, DecodeInvalidArrayBuffer) {
1720
  InvalidDecodeTest({0xFF, 0x09, 0x42, 0xFF, 0xFF, 0x00});
1721 1722
}

1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
// An array buffer allocator that never has available memory.
class OOMArrayBufferAllocator : public ArrayBuffer::Allocator {
 public:
  void* Allocate(size_t) override { return nullptr; }
  void* AllocateUninitialized(size_t) override { return nullptr; }
  void Free(void*, size_t) override {}
};

TEST_F(ValueSerializerTest, DecodeArrayBufferOOM) {
  // This test uses less of the harness, because it has to customize the
  // isolate.
  OOMArrayBufferAllocator allocator;
  Isolate::CreateParams params;
  params.array_buffer_allocator = &allocator;
  Isolate* isolate = Isolate::New(params);
1738 1739 1740 1741 1742 1743 1744
  {
    Isolate::Scope isolate_scope(isolate);
    HandleScope handle_scope(isolate);
    Local<Context> context = Context::New(isolate);
    Context::Scope context_scope(context);
    TryCatch try_catch(isolate);

1745 1746
    const std::vector<uint8_t> data = {0xFF, 0x09, 0x3F, 0x00, 0x42,
                                       0x03, 0x00, 0x80, 0xFF, 0x00};
1747 1748 1749 1750 1751 1752 1753 1754 1755
    ValueDeserializer deserializer(isolate, &data[0],
                                   static_cast<int>(data.size()), nullptr);
    deserializer.SetSupportsLegacyWireFormat(true);
    ASSERT_TRUE(deserializer.ReadHeader(context).FromMaybe(false));
    ASSERT_FALSE(try_catch.HasCaught());
    EXPECT_TRUE(deserializer.ReadValue(context).IsEmpty());
    EXPECT_TRUE(try_catch.HasCaught());
  }
  isolate->Dispose();
1756 1757
}

1758 1759 1760 1761 1762 1763 1764 1765 1766
// Includes an ArrayBuffer wrapper marked for transfer from the serialization
// context to the deserialization context.
class ValueSerializerTestWithArrayBufferTransfer : public ValueSerializerTest {
 protected:
  static const size_t kTestByteLength = 4;

  ValueSerializerTestWithArrayBufferTransfer() {
    {
      Context::Scope scope(serialization_context());
1767
      input_buffer_ = ArrayBuffer::New(isolate(), 0);
1768 1769 1770 1771
    }
    {
      Context::Scope scope(deserialization_context());
      output_buffer_ = ArrayBuffer::New(isolate(), kTestByteLength);
1772
      const uint8_t data[kTestByteLength] = {0x00, 0x01, 0x80, 0xFF};
1773
      memcpy(output_buffer_->GetBackingStore()->Data(), data, kTestByteLength);
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
    }
  }

  const Local<ArrayBuffer>& input_buffer() { return input_buffer_; }
  const Local<ArrayBuffer>& output_buffer() { return output_buffer_; }

  void BeforeEncode(ValueSerializer* serializer) override {
    serializer->TransferArrayBuffer(0, input_buffer_);
  }

  void BeforeDecode(ValueDeserializer* deserializer) override {
    deserializer->TransferArrayBuffer(0, output_buffer_);
  }

 private:
  Local<ArrayBuffer> input_buffer_;
  Local<ArrayBuffer> output_buffer_;
};

TEST_F(ValueSerializerTestWithArrayBufferTransfer,
       RoundTripArrayBufferTransfer) {
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
  Local<Value> value = RoundTripTest(input_buffer());
  ASSERT_TRUE(value->IsArrayBuffer());
  EXPECT_EQ(output_buffer(), value);
  ExpectScriptTrue("new Uint8Array(result).toString() === '0,1,128,255'");

  Local<Object> object;
  {
    Context::Scope scope(serialization_context());
    object = Object::New(isolate());
    EXPECT_TRUE(object
                    ->CreateDataProperty(serialization_context(),
                                         StringFromUtf8("a"), input_buffer())
                    .FromMaybe(false));
    EXPECT_TRUE(object
                    ->CreateDataProperty(serialization_context(),
                                         StringFromUtf8("b"), input_buffer())
                    .FromMaybe(false));
  }
  value = RoundTripTest(object);
  ExpectScriptTrue("result.a instanceof ArrayBuffer");
  ExpectScriptTrue("result.a === result.b");
  ExpectScriptTrue("new Uint8Array(result.a).toString() === '0,1,128,255'");
1817 1818
}

1819
TEST_F(ValueSerializerTest, RoundTripTypedArray) {
1820 1821 1822
  // Check that the right type comes out the other side for every kind of typed
  // array.
  Local<Value> value;
1823 1824 1825 1826 1827 1828
#define TYPED_ARRAY_ROUND_TRIP_TEST(Type, type, TYPE, ctype)             \
  value = RoundTripTest("new " #Type "Array(2)");                        \
  ASSERT_TRUE(value->Is##Type##Array());                                 \
  EXPECT_EQ(2u * sizeof(ctype), TypedArray::Cast(*value)->ByteLength()); \
  EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());                     \
  ExpectScriptTrue("Object.getPrototypeOf(result) === " #Type            \
1829 1830
                   "Array.prototype");

1831
  TYPED_ARRAYS(TYPED_ARRAY_ROUND_TRIP_TEST)
1832
#undef TYPED_ARRAY_ROUND_TRIP_TEST
1833 1834

  // Check that values of various kinds are suitably preserved.
1835 1836 1837 1838 1839 1840 1841 1842
  value = RoundTripTest("new Uint8Array([1, 128, 255])");
  ExpectScriptTrue("result.toString() === '1,128,255'");

  value = RoundTripTest("new Int16Array([0, 256, -32768])");
  ExpectScriptTrue("result.toString() === '0,256,-32768'");

  value = RoundTripTest("new Float32Array([0, -0.5, NaN, Infinity])");
  ExpectScriptTrue("result.toString() === '0,-0.5,NaN,Infinity'");
1843 1844 1845

  // Array buffer views sharing a buffer should do so on the other side.
  // Similarly, multiple references to the same typed array should be resolved.
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
  value = RoundTripTest(
      "var buffer = new ArrayBuffer(32);"
      "({"
      "  u8: new Uint8Array(buffer),"
      "  get u8_2() { return this.u8; },"
      "  f32: new Float32Array(buffer, 4, 5),"
      "  b: buffer,"
      "});");
  ExpectScriptTrue("result.u8 instanceof Uint8Array");
  ExpectScriptTrue("result.u8 === result.u8_2");
  ExpectScriptTrue("result.f32 instanceof Float32Array");
  ExpectScriptTrue("result.u8.buffer === result.f32.buffer");
  ExpectScriptTrue("result.f32.byteOffset === 4");
  ExpectScriptTrue("result.f32.length === 5");
1860 1861 1862 1863 1864
}

TEST_F(ValueSerializerTest, DecodeTypedArray) {
  // Check that the right type comes out the other side for every kind of typed
  // array.
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
  Local<Value> value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x3F, 0x00, 0x42,
                                   0x02, 0x00, 0x00, 0x56, 0x42, 0x00, 0x02});
  ASSERT_TRUE(value->IsUint8Array());
  EXPECT_EQ(2u, TypedArray::Cast(*value)->ByteLength());
  EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Uint8Array.prototype");

  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x3F, 0x00, 0x42, 0x02, 0x00,
                      0x00, 0x56, 0x62, 0x00, 0x02});
  ASSERT_TRUE(value->IsInt8Array());
  EXPECT_EQ(2u, TypedArray::Cast(*value)->ByteLength());
  EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Int8Array.prototype");

1879
#if defined(V8_TARGET_LITTLE_ENDIAN)
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x3F, 0x00, 0x42, 0x04, 0x00,
                      0x00, 0x00, 0x00, 0x56, 0x57, 0x00, 0x04});
  ASSERT_TRUE(value->IsUint16Array());
  EXPECT_EQ(4u, TypedArray::Cast(*value)->ByteLength());
  EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Uint16Array.prototype");

  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x3F, 0x00, 0x42, 0x04, 0x00,
                      0x00, 0x00, 0x00, 0x56, 0x77, 0x00, 0x04});
  ASSERT_TRUE(value->IsInt16Array());
  EXPECT_EQ(4u, TypedArray::Cast(*value)->ByteLength());
  EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Int16Array.prototype");

  value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x3F, 0x00, 0x42, 0x08, 0x00, 0x00,
                  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x44, 0x00, 0x08});
  ASSERT_TRUE(value->IsUint32Array());
  EXPECT_EQ(8u, TypedArray::Cast(*value)->ByteLength());
  EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Uint32Array.prototype");

  value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x3F, 0x00, 0x42, 0x08, 0x00, 0x00,
                  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x64, 0x00, 0x08});
  ASSERT_TRUE(value->IsInt32Array());
  EXPECT_EQ(8u, TypedArray::Cast(*value)->ByteLength());
  EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Int32Array.prototype");

  value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x3F, 0x00, 0x42, 0x08, 0x00, 0x00,
                  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x66, 0x00, 0x08});
  ASSERT_TRUE(value->IsFloat32Array());
  EXPECT_EQ(8u, TypedArray::Cast(*value)->ByteLength());
  EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Float32Array.prototype");

  value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x3F, 0x00, 0x42, 0x10, 0x00, 0x00,
                  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                  0x00, 0x00, 0x00, 0x00, 0x56, 0x46, 0x00, 0x10});
  ASSERT_TRUE(value->IsFloat64Array());
  EXPECT_EQ(16u, TypedArray::Cast(*value)->ByteLength());
  EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
  ExpectScriptTrue("Object.getPrototypeOf(result) === Float64Array.prototype");

1927 1928 1929
#endif  // V8_TARGET_LITTLE_ENDIAN

  // Check that values of various kinds are suitably preserved.
1930 1931 1932 1933
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x3F, 0x00, 0x42, 0x03, 0x01,
                      0x80, 0xFF, 0x56, 0x42, 0x00, 0x03, 0x00});
  ExpectScriptTrue("result.toString() === '1,128,255'");

1934
#if defined(V8_TARGET_LITTLE_ENDIAN)
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
  value = DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x3F, 0x00, 0x42, 0x06, 0x00,
                      0x00, 0x00, 0x01, 0x00, 0x80, 0x56, 0x77, 0x00, 0x06});
  ExpectScriptTrue("result.toString() === '0,256,-32768'");

  value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x3F, 0x00, 0x42, 0x10, 0x00, 0x00,
                  0x00, 0x00, 0x00, 0x00, 0x00, 0xBF, 0x00, 0x00, 0xC0, 0x7F,
                  0x00, 0x00, 0x80, 0x7F, 0x56, 0x66, 0x00, 0x10});
  ExpectScriptTrue("result.toString() === '0,-0.5,NaN,Infinity'");

1945 1946 1947 1948
#endif  // V8_TARGET_LITTLE_ENDIAN

  // Array buffer views sharing a buffer should do so on the other side.
  // Similarly, multiple references to the same typed array should be resolved.
1949
  value = DecodeTest(
1950 1951
      {0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x53, 0x02, 0x75, 0x38, 0x3F,
       0x01, 0x3F, 0x01, 0x42, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1952 1953
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1954 1955 1956
       0x00, 0x56, 0x42, 0x00, 0x20, 0x3F, 0x03, 0x53, 0x04, 0x75, 0x38, 0x5F,
       0x32, 0x3F, 0x03, 0x5E, 0x02, 0x3F, 0x03, 0x53, 0x03, 0x66, 0x33, 0x32,
       0x3F, 0x03, 0x3F, 0x03, 0x5E, 0x01, 0x56, 0x66, 0x04, 0x14, 0x3F, 0x04,
1957 1958 1959 1960 1961 1962 1963
       0x53, 0x01, 0x62, 0x3F, 0x04, 0x5E, 0x01, 0x7B, 0x04, 0x00});
  ExpectScriptTrue("result.u8 instanceof Uint8Array");
  ExpectScriptTrue("result.u8 === result.u8_2");
  ExpectScriptTrue("result.f32 instanceof Float32Array");
  ExpectScriptTrue("result.u8.buffer === result.f32.buffer");
  ExpectScriptTrue("result.f32.byteOffset === 4");
  ExpectScriptTrue("result.f32.length === 5");
1964 1965 1966 1967 1968
}

TEST_F(ValueSerializerTest, DecodeInvalidTypedArray) {
  // Byte offset out of range.
  InvalidDecodeTest(
1969
      {0xFF, 0x09, 0x42, 0x02, 0x00, 0x00, 0x56, 0x42, 0x03, 0x01});
1970 1971
  // Byte offset in range, offset + length out of range.
  InvalidDecodeTest(
1972
      {0xFF, 0x09, 0x42, 0x02, 0x00, 0x00, 0x56, 0x42, 0x01, 0x03});
1973 1974
  // Byte offset not divisible by element size.
  InvalidDecodeTest(
1975
      {0xFF, 0x09, 0x42, 0x04, 0x00, 0x00, 0x00, 0x00, 0x56, 0x77, 0x01, 0x02});
1976 1977
  // Byte length not divisible by element size.
  InvalidDecodeTest(
1978 1979
      {0xFF, 0x09, 0x42, 0x04, 0x00, 0x00, 0x00, 0x00, 0x56, 0x77, 0x02, 0x01});
  // Invalid view type (0xFF).
1980
  InvalidDecodeTest(
1981
      {0xFF, 0x09, 0x42, 0x02, 0x00, 0x00, 0x56, 0xFF, 0x01, 0x01});
1982 1983 1984
}

TEST_F(ValueSerializerTest, RoundTripDataView) {
1985 1986 1987 1988 1989 1990
  Local<Value> value = RoundTripTest("new DataView(new ArrayBuffer(4), 1, 2)");
  ASSERT_TRUE(value->IsDataView());
  EXPECT_EQ(1u, DataView::Cast(*value)->ByteOffset());
  EXPECT_EQ(2u, DataView::Cast(*value)->ByteLength());
  EXPECT_EQ(4u, DataView::Cast(*value)->Buffer()->ByteLength());
  ExpectScriptTrue("Object.getPrototypeOf(result) === DataView.prototype");
1991 1992 1993
}

TEST_F(ValueSerializerTest, DecodeDataView) {
1994 1995 1996 1997 1998 1999 2000 2001
  Local<Value> value =
      DecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x3F, 0x00, 0x42, 0x04, 0x00, 0x00,
                  0x00, 0x00, 0x56, 0x3F, 0x01, 0x02});
  ASSERT_TRUE(value->IsDataView());
  EXPECT_EQ(1u, DataView::Cast(*value)->ByteOffset());
  EXPECT_EQ(2u, DataView::Cast(*value)->ByteLength());
  EXPECT_EQ(4u, DataView::Cast(*value)->Buffer()->ByteLength());
  ExpectScriptTrue("Object.getPrototypeOf(result) === DataView.prototype");
2002 2003
}

2004
TEST_F(ValueSerializerTest, DecodeArrayWithLengthProperty1) {
2005 2006 2007
  InvalidDecodeTest({0xff, 0x0d, 0x41, 0x03, 0x49, 0x02, 0x49, 0x04,
                     0x49, 0x06, 0x22, 0x06, 0x6c, 0x65, 0x6e, 0x67,
                     0x74, 0x68, 0x49, 0x02, 0x24, 0x01, 0x03});
2008 2009 2010
}

TEST_F(ValueSerializerTest, DecodeArrayWithLengthProperty2) {
2011 2012 2013
  InvalidDecodeTest({0xff, 0x0d, 0x41, 0x03, 0x49, 0x02, 0x49, 0x04,
                     0x49, 0x06, 0x22, 0x06, 0x6c, 0x65, 0x6e, 0x67,
                     0x74, 0x68, 0x6f, 0x7b, 0x00, 0x24, 0x01, 0x03});
2014 2015
}

2016 2017 2018
TEST_F(ValueSerializerTest, DecodeInvalidDataView) {
  // Byte offset out of range.
  InvalidDecodeTest(
2019
      {0xFF, 0x09, 0x42, 0x02, 0x00, 0x00, 0x56, 0x3F, 0x03, 0x01});
2020 2021
  // Byte offset in range, offset + length out of range.
  InvalidDecodeTest(
2022
      {0xFF, 0x09, 0x42, 0x02, 0x00, 0x00, 0x56, 0x3F, 0x01, 0x03});
2023 2024
}

2025
class ValueSerializerTestWithSharedArrayBufferClone
2026 2027
    : public ValueSerializerTest {
 protected:
2028 2029
  ValueSerializerTestWithSharedArrayBufferClone()
      : serializer_delegate_(this), deserializer_delegate_(this) {}
2030

2031
  void InitializeData(const std::vector<uint8_t>& data, bool is_wasm_memory) {
2032
    data_ = data;
2033 2034 2035
    {
      Context::Scope scope(serialization_context());
      input_buffer_ =
2036
          NewSharedArrayBuffer(data_.data(), data_.size(), is_wasm_memory);
2037 2038 2039 2040
    }
    {
      Context::Scope scope(deserialization_context());
      output_buffer_ =
2041
          NewSharedArrayBuffer(data_.data(), data_.size(), is_wasm_memory);
2042 2043 2044 2045 2046 2047
    }
  }

  const Local<SharedArrayBuffer>& input_buffer() { return input_buffer_; }
  const Local<SharedArrayBuffer>& output_buffer() { return output_buffer_; }

2048 2049
  Local<SharedArrayBuffer> NewSharedArrayBuffer(void* data, size_t byte_length,
                                                bool is_wasm_memory) {
2050
#if V8_ENABLE_WEBASSEMBLY
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
    if (is_wasm_memory) {
      // TODO(titzer): there is no way to create Wasm memory backing stores
      // through the API, or to create a shared array buffer whose backing
      // store is wasm memory, so use the internal API.
      DCHECK_EQ(0, byte_length % i::wasm::kWasmPageSize);
      auto pages = byte_length / i::wasm::kWasmPageSize;
      auto i_isolate = reinterpret_cast<i::Isolate*>(isolate());
      auto backing_store = i::BackingStore::AllocateWasmMemory(
          i_isolate, pages, pages, i::SharedFlag::kShared);
      memcpy(backing_store->buffer_start(), data, byte_length);
      i::Handle<i::JSArrayBuffer> buffer =
2062 2063
          i_isolate->factory()->NewJSSharedArrayBuffer(
              std::move(backing_store));
2064 2065
      return Utils::ToLocalShared(buffer);
    }
2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077
#endif  // V8_ENABLE_WEBASSEMBLY

    CHECK(!is_wasm_memory);
    std::unique_ptr<v8::BackingStore> backing_store =
        SharedArrayBuffer::NewBackingStore(
            data, byte_length,
            [](void*, size_t, void*) {
              // Leak the buffer as it has the
              // lifetime of the test.
            },
            nullptr);
    return SharedArrayBuffer::New(isolate(), std::move(backing_store));
2078 2079
  }

2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
  static void SetUpTestCase() {
    flag_was_enabled_ = i::FLAG_harmony_sharedarraybuffer;
    i::FLAG_harmony_sharedarraybuffer = true;
    ValueSerializerTest::SetUpTestCase();
  }

  static void TearDownTestCase() {
    ValueSerializerTest::TearDownTestCase();
    i::FLAG_harmony_sharedarraybuffer = flag_was_enabled_;
    flag_was_enabled_ = false;
  }

2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
 protected:
// GMock doesn't use the "override" keyword.
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winconsistent-missing-override"
#endif

  class SerializerDelegate : public ValueSerializer::Delegate {
   public:
    explicit SerializerDelegate(
2102
        ValueSerializerTestWithSharedArrayBufferClone* test)
2103
        : test_(test) {}
2104 2105 2106 2107 2108
    MOCK_METHOD(Maybe<uint32_t>, GetSharedArrayBufferId,
                (Isolate*, Local<SharedArrayBuffer> shared_array_buffer),
                (override));
    MOCK_METHOD(MaybeLocal<SharedArrayBuffer>, GetSharedArrayBufferFromId,
                (Isolate*, uint32_t id));
2109 2110 2111 2112 2113
    void ThrowDataCloneError(Local<String> message) override {
      test_->isolate()->ThrowException(Exception::Error(message));
    }

   private:
2114 2115 2116 2117 2118 2119 2120
    ValueSerializerTestWithSharedArrayBufferClone* test_;
  };

  class DeserializerDelegate : public ValueDeserializer::Delegate {
   public:
    explicit DeserializerDelegate(
        ValueSerializerTestWithSharedArrayBufferClone* test) {}
2121 2122
    MOCK_METHOD(MaybeLocal<SharedArrayBuffer>, GetSharedArrayBufferFromId,
                (Isolate*, uint32_t id), (override));
2123 2124 2125 2126 2127 2128 2129 2130 2131 2132
  };

#if __clang__
#pragma clang diagnostic pop
#endif

  ValueSerializer::Delegate* GetSerializerDelegate() override {
    return &serializer_delegate_;
  }

2133 2134 2135 2136
  ValueDeserializer::Delegate* GetDeserializerDelegate() override {
    return &deserializer_delegate_;
  }

2137
  SerializerDelegate serializer_delegate_;
2138
  DeserializerDelegate deserializer_delegate_;
2139

2140 2141
 private:
  static bool flag_was_enabled_;
2142
  std::vector<uint8_t> data_;
2143 2144 2145 2146
  Local<SharedArrayBuffer> input_buffer_;
  Local<SharedArrayBuffer> output_buffer_;
};

2147
bool ValueSerializerTestWithSharedArrayBufferClone::flag_was_enabled_ = false;
2148

2149 2150
TEST_F(ValueSerializerTestWithSharedArrayBufferClone,
       RoundTripSharedArrayBufferClone) {
2151
  InitializeData({0x00, 0x01, 0x80, 0xFF}, false);
2152

2153 2154 2155
  EXPECT_CALL(serializer_delegate_,
              GetSharedArrayBufferId(isolate(), input_buffer()))
      .WillRepeatedly(Return(Just(0U)));
2156 2157
  EXPECT_CALL(deserializer_delegate_, GetSharedArrayBufferFromId(isolate(), 0U))
      .WillRepeatedly(Return(output_buffer()));
2158

2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180
  Local<Value> value = RoundTripTest(input_buffer());
  ASSERT_TRUE(value->IsSharedArrayBuffer());
  EXPECT_EQ(output_buffer(), value);
  ExpectScriptTrue("new Uint8Array(result).toString() === '0,1,128,255'");

  Local<Object> object;
  {
    Context::Scope scope(serialization_context());
    object = Object::New(isolate());
    EXPECT_TRUE(object
                    ->CreateDataProperty(serialization_context(),
                                         StringFromUtf8("a"), input_buffer())
                    .FromMaybe(false));
    EXPECT_TRUE(object
                    ->CreateDataProperty(serialization_context(),
                                         StringFromUtf8("b"), input_buffer())
                    .FromMaybe(false));
  }
  value = RoundTripTest(object);
  ExpectScriptTrue("result.a instanceof SharedArrayBuffer");
  ExpectScriptTrue("result.a === result.b");
  ExpectScriptTrue("new Uint8Array(result.a).toString() === '0,1,128,255'");
2181 2182
}

2183
#if V8_ENABLE_WEBASSEMBLY
2184
TEST_F(ValueSerializerTestWithSharedArrayBufferClone,
2185 2186 2187 2188
       RoundTripWebAssemblyMemory) {
  bool flag_was_enabled = i::FLAG_experimental_wasm_threads;
  i::FLAG_experimental_wasm_threads = true;

2189
  std::vector<uint8_t> data = {0x00, 0x01, 0x80, 0xFF};
2190
  data.resize(65536);
2191
  InitializeData(data, true);
2192 2193 2194 2195

  EXPECT_CALL(serializer_delegate_,
              GetSharedArrayBufferId(isolate(), input_buffer()))
      .WillRepeatedly(Return(Just(0U)));
2196 2197
  EXPECT_CALL(deserializer_delegate_, GetSharedArrayBufferFromId(isolate(), 0U))
      .WillRepeatedly(Return(output_buffer()));
2198

2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212
  Local<Value> input;
  {
    Context::Scope scope(serialization_context());
    const int32_t kMaxPages = 1;
    i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate());
    i::Handle<i::JSArrayBuffer> obj = Utils::OpenHandle(*input_buffer());
    input = Utils::Convert<i::WasmMemoryObject, Value>(
        i::WasmMemoryObject::New(i_isolate, obj, kMaxPages));
  }
  RoundTripTest(input);
  ExpectScriptTrue("result instanceof WebAssembly.Memory");
  ExpectScriptTrue("result.buffer.byteLength === 65536");
  ExpectScriptTrue(
      "new Uint8Array(result.buffer, 0, 4).toString() === '0,1,128,255'");
2213 2214 2215

  i::FLAG_experimental_wasm_threads = flag_was_enabled;
}
2216
#endif  // V8_ENABLE_WEBASSEMBLY
2217

2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
TEST_F(ValueSerializerTest, UnsupportedHostObject) {
  InvalidEncodeTest("new ExampleHostObject()");
  InvalidEncodeTest("({ a: new ExampleHostObject() })");
}

class ValueSerializerTestWithHostObject : public ValueSerializerTest {
 protected:
  ValueSerializerTestWithHostObject() : serializer_delegate_(this) {}

  static const uint8_t kExampleHostObjectTag;

  void WriteExampleHostObjectTag() {
    serializer_->WriteRawBytes(&kExampleHostObjectTag, 1);
  }

  bool ReadExampleHostObjectTag() {
    const void* tag;
    return deserializer_->ReadRawBytes(1, &tag) &&
           *reinterpret_cast<const uint8_t*>(tag) == kExampleHostObjectTag;
  }

// GMock doesn't use the "override" keyword.
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winconsistent-missing-override"
#endif

  class SerializerDelegate : public ValueSerializer::Delegate {
   public:
    explicit SerializerDelegate(ValueSerializerTestWithHostObject* test)
        : test_(test) {}
2249 2250
    MOCK_METHOD(Maybe<bool>, WriteHostObject, (Isolate*, Local<Object> object),
                (override));
2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
    void ThrowDataCloneError(Local<String> message) override {
      test_->isolate()->ThrowException(Exception::Error(message));
    }

   private:
    ValueSerializerTestWithHostObject* test_;
  };

  class DeserializerDelegate : public ValueDeserializer::Delegate {
   public:
2261
    MOCK_METHOD(MaybeLocal<Object>, ReadHostObject, (Isolate*), (override));
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
  };

#if __clang__
#pragma clang diagnostic pop
#endif

  ValueSerializer::Delegate* GetSerializerDelegate() override {
    return &serializer_delegate_;
  }
  void BeforeEncode(ValueSerializer* serializer) override {
    serializer_ = serializer;
  }
  ValueDeserializer::Delegate* GetDeserializerDelegate() override {
    return &deserializer_delegate_;
  }
  void BeforeDecode(ValueDeserializer* deserializer) override {
    deserializer_ = deserializer;
  }

  SerializerDelegate serializer_delegate_;
  DeserializerDelegate deserializer_delegate_;
  ValueSerializer* serializer_;
  ValueDeserializer* deserializer_;

  friend class SerializerDelegate;
  friend class DeserializerDelegate;
};

2290 2291 2292
// This is a tag that is used in V8. Using this ensures that we have separate
// tag namespaces.
const uint8_t ValueSerializerTestWithHostObject::kExampleHostObjectTag = 'T';
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313

TEST_F(ValueSerializerTestWithHostObject, RoundTripUint32) {
  // The host can serialize data as uint32_t.
  EXPECT_CALL(serializer_delegate_, WriteHostObject(isolate(), _))
      .WillRepeatedly(Invoke([this](Isolate*, Local<Object> object) {
        uint32_t value = 0;
        EXPECT_TRUE(object->GetInternalField(0)
                        ->Uint32Value(serialization_context())
                        .To(&value));
        WriteExampleHostObjectTag();
        serializer_->WriteUint32(value);
        return Just(true);
      }));
  EXPECT_CALL(deserializer_delegate_, ReadHostObject(isolate()))
      .WillRepeatedly(Invoke([this](Isolate*) {
        EXPECT_TRUE(ReadExampleHostObjectTag());
        uint32_t value = 0;
        EXPECT_TRUE(deserializer_->ReadUint32(&value));
        Local<Value> argv[] = {Integer::NewFromUnsigned(isolate(), value)};
        return NewHostObject(deserialization_context(), arraysize(argv), argv);
      }));
2314 2315 2316 2317 2318 2319 2320 2321 2322
  Local<Value> value = RoundTripTest("new ExampleHostObject(42)");
  ASSERT_TRUE(value->IsObject());
  ASSERT_TRUE(Object::Cast(*value)->InternalFieldCount());
  ExpectScriptTrue(
      "Object.getPrototypeOf(result) === ExampleHostObject.prototype");
  ExpectScriptTrue("result.value === 42");

  value = RoundTripTest("new ExampleHostObject(0xCAFECAFE)");
  ExpectScriptTrue("result.value === 0xCAFECAFE");
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
}

TEST_F(ValueSerializerTestWithHostObject, RoundTripUint64) {
  // The host can serialize data as uint64_t.
  EXPECT_CALL(serializer_delegate_, WriteHostObject(isolate(), _))
      .WillRepeatedly(Invoke([this](Isolate*, Local<Object> object) {
        uint32_t value = 0, value2 = 0;
        EXPECT_TRUE(object->GetInternalField(0)
                        ->Uint32Value(serialization_context())
                        .To(&value));
        EXPECT_TRUE(object->GetInternalField(1)
                        ->Uint32Value(serialization_context())
                        .To(&value2));
        WriteExampleHostObjectTag();
        serializer_->WriteUint64((static_cast<uint64_t>(value) << 32) | value2);
        return Just(true);
      }));
  EXPECT_CALL(deserializer_delegate_, ReadHostObject(isolate()))
      .WillRepeatedly(Invoke([this](Isolate*) {
        EXPECT_TRUE(ReadExampleHostObjectTag());
        uint64_t value_packed;
        EXPECT_TRUE(deserializer_->ReadUint64(&value_packed));
        Local<Value> argv[] = {
            Integer::NewFromUnsigned(isolate(),
                                     static_cast<uint32_t>(value_packed >> 32)),
            Integer::NewFromUnsigned(isolate(),
                                     static_cast<uint32_t>(value_packed))};
        return NewHostObject(deserialization_context(), arraysize(argv), argv);
      }));
2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362
  Local<Value> value = RoundTripTest("new ExampleHostObject(42, 0)");
  ASSERT_TRUE(value->IsObject());
  ASSERT_TRUE(Object::Cast(*value)->InternalFieldCount());
  ExpectScriptTrue(
      "Object.getPrototypeOf(result) === ExampleHostObject.prototype");
  ExpectScriptTrue("result.value === 42");
  ExpectScriptTrue("result.value2 === 0");

  value = RoundTripTest("new ExampleHostObject(0xFFFFFFFF, 0x12345678)");
  ExpectScriptTrue("result.value === 0xFFFFFFFF");
  ExpectScriptTrue("result.value2 === 0x12345678");
2363 2364
}

2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384
TEST_F(ValueSerializerTestWithHostObject, RoundTripDouble) {
  // The host can serialize data as double.
  EXPECT_CALL(serializer_delegate_, WriteHostObject(isolate(), _))
      .WillRepeatedly(Invoke([this](Isolate*, Local<Object> object) {
        double value = 0;
        EXPECT_TRUE(object->GetInternalField(0)
                        ->NumberValue(serialization_context())
                        .To(&value));
        WriteExampleHostObjectTag();
        serializer_->WriteDouble(value);
        return Just(true);
      }));
  EXPECT_CALL(deserializer_delegate_, ReadHostObject(isolate()))
      .WillRepeatedly(Invoke([this](Isolate*) {
        EXPECT_TRUE(ReadExampleHostObjectTag());
        double value = 0;
        EXPECT_TRUE(deserializer_->ReadDouble(&value));
        Local<Value> argv[] = {Number::New(isolate(), value)};
        return NewHostObject(deserialization_context(), arraysize(argv), argv);
      }));
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
  Local<Value> value = RoundTripTest("new ExampleHostObject(-3.5)");
  ASSERT_TRUE(value->IsObject());
  ASSERT_TRUE(Object::Cast(*value)->InternalFieldCount());
  ExpectScriptTrue(
      "Object.getPrototypeOf(result) === ExampleHostObject.prototype");
  ExpectScriptTrue("result.value === -3.5");

  value = RoundTripTest("new ExampleHostObject(NaN)");
  ExpectScriptTrue("Number.isNaN(result.value)");

  value = RoundTripTest("new ExampleHostObject(Infinity)");
  ExpectScriptTrue("result.value === Infinity");

  value = RoundTripTest("new ExampleHostObject(-0)");
  ExpectScriptTrue("1/result.value === -Infinity");
2400 2401
}

2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426
TEST_F(ValueSerializerTestWithHostObject, RoundTripRawBytes) {
  // The host can serialize arbitrary raw bytes.
  const struct {
    uint64_t u64;
    uint32_t u32;
    char str[12];
  } sample_data = {0x1234567812345678, 0x87654321, "Hello world"};
  EXPECT_CALL(serializer_delegate_, WriteHostObject(isolate(), _))
      .WillRepeatedly(
          Invoke([this, &sample_data](Isolate*, Local<Object> object) {
            WriteExampleHostObjectTag();
            serializer_->WriteRawBytes(&sample_data, sizeof(sample_data));
            return Just(true);
          }));
  EXPECT_CALL(deserializer_delegate_, ReadHostObject(isolate()))
      .WillRepeatedly(Invoke([this, &sample_data](Isolate*) {
        EXPECT_TRUE(ReadExampleHostObjectTag());
        const void* copied_data = nullptr;
        EXPECT_TRUE(
            deserializer_->ReadRawBytes(sizeof(sample_data), &copied_data));
        if (copied_data) {
          EXPECT_EQ(0, memcmp(&sample_data, copied_data, sizeof(sample_data)));
        }
        return NewHostObject(deserialization_context(), 0, nullptr);
      }));
2427 2428 2429 2430 2431
  Local<Value> value = RoundTripTest("new ExampleHostObject()");
  ASSERT_TRUE(value->IsObject());
  ASSERT_TRUE(Object::Cast(*value)->InternalFieldCount());
  ExpectScriptTrue(
      "Object.getPrototypeOf(result) === ExampleHostObject.prototype");
2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447
}

TEST_F(ValueSerializerTestWithHostObject, RoundTripSameObject) {
  // If the same object exists in two places, the delegate should be invoked
  // only once, and the objects should be the same (by reference equality) on
  // the other side.
  EXPECT_CALL(serializer_delegate_, WriteHostObject(isolate(), _))
      .WillOnce(Invoke([this](Isolate*, Local<Object> object) {
        WriteExampleHostObjectTag();
        return Just(true);
      }));
  EXPECT_CALL(deserializer_delegate_, ReadHostObject(isolate()))
      .WillOnce(Invoke([this](Isolate*) {
        EXPECT_TRUE(ReadExampleHostObjectTag());
        return NewHostObject(deserialization_context(), 0, nullptr);
      }));
2448 2449 2450
  RoundTripTest("({ a: new ExampleHostObject(), get b() { return this.a; }})");
  ExpectScriptTrue("result.a instanceof ExampleHostObject");
  ExpectScriptTrue("result.a === result.b");
2451 2452
}

2453 2454 2455 2456 2457 2458
TEST_F(ValueSerializerTestWithHostObject, DecodeSimpleHostObject) {
  EXPECT_CALL(deserializer_delegate_, ReadHostObject(isolate()))
      .WillRepeatedly(Invoke([this](Isolate*) {
        EXPECT_TRUE(ReadExampleHostObjectTag());
        return NewHostObject(deserialization_context(), 0, nullptr);
      }));
2459 2460 2461
  DecodeTest({0xFF, 0x0D, 0x5C, kExampleHostObjectTag});
  ExpectScriptTrue(
      "Object.getPrototypeOf(result) === ExampleHostObject.prototype");
2462 2463
}

2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485
class ValueSerializerTestWithHostArrayBufferView
    : public ValueSerializerTestWithHostObject {
 protected:
  void BeforeEncode(ValueSerializer* serializer) override {
    ValueSerializerTestWithHostObject::BeforeEncode(serializer);
    serializer_->SetTreatArrayBufferViewsAsHostObjects(true);
  }
};

TEST_F(ValueSerializerTestWithHostArrayBufferView, RoundTripUint8ArrayInput) {
  EXPECT_CALL(serializer_delegate_, WriteHostObject(isolate(), _))
      .WillOnce(Invoke([this](Isolate*, Local<Object> object) {
        EXPECT_TRUE(object->IsUint8Array());
        WriteExampleHostObjectTag();
        return Just(true);
      }));
  EXPECT_CALL(deserializer_delegate_, ReadHostObject(isolate()))
      .WillOnce(Invoke([this](Isolate*) {
        EXPECT_TRUE(ReadExampleHostObjectTag());
        return NewDummyUint8Array();
      }));
  RoundTripTest(
2486 2487 2488 2489
      "({ a: new Uint8Array([1, 2, 3]), get b() { return this.a; }})");
  ExpectScriptTrue("result.a instanceof Uint8Array");
  ExpectScriptTrue("result.a.toString() === '4,5,6'");
  ExpectScriptTrue("result.a === result.b");
2490 2491
}

2492
#if V8_ENABLE_WEBASSEMBLY
2493 2494 2495 2496
// It's expected that WebAssembly has more exhaustive tests elsewhere; this
// mostly checks that the logic to embed it in structured clone serialization
// works correctly.

2497 2498
// A simple module which exports an "increment" function.
// Copied from test/mjsunit/wasm/incrementer.wasm.
2499
constexpr uint8_t kIncrementerWasm[] = {
2500 2501 2502 2503 2504
    0,   97, 115, 109, 1, 0,  0, 0, 1,   6,   1,  96,  1,   127, 1,   127,
    3,   2,  1,   0,   7, 13, 1, 9, 105, 110, 99, 114, 101, 109, 101, 110,
    116, 0,  0,   10,  9, 1,  7, 0, 32,  0,   65, 1,   106, 11,
};

2505
class ValueSerializerTestWithWasm : public ValueSerializerTest {
2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533
 public:
  static const char* kUnsupportedSerialization;

  ValueSerializerTestWithWasm()
      : serialize_delegate_(&transfer_modules_),
        deserialize_delegate_(&transfer_modules_) {}

  void Reset() {
    current_serializer_delegate_ = nullptr;
    transfer_modules_.clear();
  }

  void EnableTransferSerialization() {
    current_serializer_delegate_ = &serialize_delegate_;
  }

  void EnableTransferDeserialization() {
    current_deserializer_delegate_ = &deserialize_delegate_;
  }

  void EnableThrowingSerializer() {
    current_serializer_delegate_ = &throwing_serializer_;
  }

  void EnableDefaultDeserializer() {
    current_deserializer_delegate_ = &default_deserializer_;
  }

2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546
 protected:
  static void SetUpTestCase() {
    g_saved_flag = i::FLAG_expose_wasm;
    i::FLAG_expose_wasm = true;
    ValueSerializerTest::SetUpTestCase();
  }

  static void TearDownTestCase() {
    ValueSerializerTest::TearDownTestCase();
    i::FLAG_expose_wasm = g_saved_flag;
    g_saved_flag = false;
  }

2547 2548 2549
  class ThrowingSerializer : public ValueSerializer::Delegate {
   public:
    Maybe<uint32_t> GetWasmModuleTransferId(
2550
        Isolate* isolate, Local<WasmModuleObject> module) override {
2551
      isolate->ThrowException(Exception::Error(
2552 2553
          String::NewFromOneByte(isolate, reinterpret_cast<const uint8_t*>(
                                              kUnsupportedSerialization))
2554 2555 2556 2557 2558 2559 2560 2561 2562
              .ToLocalChecked()));
      return Nothing<uint32_t>();
    }

    void ThrowDataCloneError(Local<String> message) override { UNREACHABLE(); }
  };

  class SerializeToTransfer : public ValueSerializer::Delegate {
   public:
2563
    explicit SerializeToTransfer(std::vector<CompiledWasmModule>* modules)
2564 2565
        : modules_(modules) {}
    Maybe<uint32_t> GetWasmModuleTransferId(
2566
        Isolate* isolate, Local<WasmModuleObject> module) override {
2567
      modules_->push_back(module->GetCompiledModule());
2568 2569 2570 2571 2572 2573
      return Just(static_cast<uint32_t>(modules_->size()) - 1);
    }

    void ThrowDataCloneError(Local<String> message) override { UNREACHABLE(); }

   private:
2574
    std::vector<CompiledWasmModule>* modules_;
2575 2576 2577 2578
  };

  class DeserializeFromTransfer : public ValueDeserializer::Delegate {
   public:
2579
    explicit DeserializeFromTransfer(std::vector<CompiledWasmModule>* modules)
2580 2581
        : modules_(modules) {}

2582 2583
    MaybeLocal<WasmModuleObject> GetWasmModuleFromId(Isolate* isolate,
                                                     uint32_t id) override {
2584
      return WasmModuleObject::FromCompiledModule(isolate, modules_->at(id));
2585 2586 2587
    }

   private:
2588
    std::vector<CompiledWasmModule>* modules_;
2589 2590 2591 2592 2593 2594 2595 2596 2597 2598
  };

  ValueSerializer::Delegate* GetSerializerDelegate() override {
    return current_serializer_delegate_;
  }

  ValueDeserializer::Delegate* GetDeserializerDelegate() override {
    return current_deserializer_delegate_;
  }

2599
  Local<WasmModuleObject> MakeWasm() {
2600
    Context::Scope scope(serialization_context());
2601 2602 2603 2604 2605 2606 2607 2608 2609
    i::wasm::ErrorThrower thrower(i_isolate(), "MakeWasm");
    auto enabled_features = i::wasm::WasmFeatures::FromIsolate(i_isolate());
    i::MaybeHandle<i::JSObject> compiled =
        i_isolate()->wasm_engine()->SyncCompile(
            i_isolate(), enabled_features, &thrower,
            i::wasm::ModuleWireBytes(i::ArrayVector(kIncrementerWasm)));
    CHECK(!thrower.error());
    return Local<WasmModuleObject>::Cast(
        Utils::ToLocal(compiled.ToHandleChecked()));
2610 2611 2612
  }

  void ExpectPass() {
2613 2614
    Local<Value> value = RoundTripTest(MakeWasm());
    Context::Scope scope(deserialization_context());
2615
    ASSERT_TRUE(value->IsWasmModuleObject());
2616 2617
    ExpectScriptTrue(
        "new WebAssembly.Instance(result).exports.increment(8) === 9");
2618 2619 2620
  }

  void ExpectFail() {
2621 2622
    const std::vector<uint8_t> data = EncodeTest(MakeWasm());
    InvalidDecodeTest(data);
2623 2624 2625
  }

  Local<Value> GetComplexObjectWithDuplicate() {
2626
    Context::Scope scope(serialization_context());
2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
    Local<Value> wasm_module = MakeWasm();
    serialization_context()
        ->Global()
        ->CreateDataProperty(serialization_context(),
                             StringFromUtf8("wasm_module"), wasm_module)
        .FromMaybe(false);
    Local<Script> script =
        Script::Compile(
            serialization_context(),
            StringFromUtf8("({mod1: wasm_module, num: 2, mod2: wasm_module})"))
            .ToLocalChecked();
    return script->Run(serialization_context()).ToLocalChecked();
  }

  void VerifyComplexObject(Local<Value> value) {
    ASSERT_TRUE(value->IsObject());
2643 2644 2645
    ExpectScriptTrue("result.mod1 instanceof WebAssembly.Module");
    ExpectScriptTrue("result.mod2 instanceof WebAssembly.Module");
    ExpectScriptTrue("result.num === 2");
2646 2647 2648
  }

  Local<Value> GetComplexObjectWithMany() {
2649
    Context::Scope scope(serialization_context());
2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670
    Local<Value> wasm_module1 = MakeWasm();
    Local<Value> wasm_module2 = MakeWasm();
    serialization_context()
        ->Global()
        ->CreateDataProperty(serialization_context(),
                             StringFromUtf8("wasm_module1"), wasm_module1)
        .FromMaybe(false);
    serialization_context()
        ->Global()
        ->CreateDataProperty(serialization_context(),
                             StringFromUtf8("wasm_module2"), wasm_module2)
        .FromMaybe(false);
    Local<Script> script =
        Script::Compile(
            serialization_context(),
            StringFromUtf8(
                "({mod1: wasm_module1, num: 2, mod2: wasm_module2})"))
            .ToLocalChecked();
    return script->Run(serialization_context()).ToLocalChecked();
  }

2671 2672
 private:
  static bool g_saved_flag;
2673
  std::vector<CompiledWasmModule> transfer_modules_;
2674 2675 2676 2677 2678 2679
  SerializeToTransfer serialize_delegate_;
  DeserializeFromTransfer deserialize_delegate_;
  ValueSerializer::Delegate* current_serializer_delegate_ = nullptr;
  ValueDeserializer::Delegate* current_deserializer_delegate_ = nullptr;
  ThrowingSerializer throwing_serializer_;
  ValueDeserializer::Delegate default_deserializer_;
2680 2681 2682
};

bool ValueSerializerTestWithWasm::g_saved_flag = false;
2683 2684 2685 2686 2687 2688 2689 2690
const char* ValueSerializerTestWithWasm::kUnsupportedSerialization =
    "Wasm Serialization Not Supported";

// The default implementation of the serialization
// delegate throws when trying to serialize wasm. The
// embedder must decide serialization policy.
TEST_F(ValueSerializerTestWithWasm, DefaultSerializationDelegate) {
  EnableThrowingSerializer();
2691 2692 2693
  Local<Message> message = InvalidEncodeTest(MakeWasm());
  size_t msg_len = static_cast<size_t>(message->Get()->Length());
  std::unique_ptr<char[]> buff(new char[msg_len + 1]);
2694 2695
  message->Get()->WriteOneByte(isolate(),
                               reinterpret_cast<uint8_t*>(buff.get()));
2696 2697 2698 2699 2700
  // the message ends with the custom error string
  size_t custom_msg_len = strlen(kUnsupportedSerialization);
  ASSERT_GE(msg_len, custom_msg_len);
  size_t start_pos = msg_len - custom_msg_len;
  ASSERT_EQ(strcmp(&buff.get()[start_pos], kUnsupportedSerialization), 0);
2701
}
2702

2703 2704 2705 2706
// The default deserializer throws if wasm transfer is attempted
TEST_F(ValueSerializerTestWithWasm, DefaultDeserializationDelegate) {
  EnableTransferSerialization();
  EnableDefaultDeserializer();
2707
  ExpectFail();
2708
}
mtrofin's avatar
mtrofin committed
2709

2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
// We only want to allow deserialization through
// transferred modules - which requres both serializer
// and deserializer to understand that - or through
// explicitly allowing inlined data, which requires
// deserializer opt-in (we default the serializer to
// inlined data because we don't trust that data on the
// receiving end anyway).

TEST_F(ValueSerializerTestWithWasm, RoundtripWasmTransfer) {
  EnableTransferSerialization();
  EnableTransferDeserialization();
  ExpectPass();
}

TEST_F(ValueSerializerTestWithWasm, CannotTransferWasmWhenExpectingInline) {
  EnableTransferSerialization();
  ExpectFail();
}

TEST_F(ValueSerializerTestWithWasm, ComplexObjectDuplicateTransfer) {
  EnableTransferSerialization();
  EnableTransferDeserialization();
2732 2733 2734
  Local<Value> value = RoundTripTest(GetComplexObjectWithDuplicate());
  VerifyComplexObject(value);
  ExpectScriptTrue("result.mod1 === result.mod2");
2735 2736 2737 2738 2739
}

TEST_F(ValueSerializerTestWithWasm, ComplexObjectWithManyTransfer) {
  EnableTransferSerialization();
  EnableTransferDeserialization();
2740 2741 2742
  Local<Value> value = RoundTripTest(GetComplexObjectWithMany());
  VerifyComplexObject(value);
  ExpectScriptTrue("result.mod1 != result.mod2");
2743
}
2744
#endif  // V8_ENABLE_WEBASSEMBLY
2745

2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781
class ValueSerializerTestWithLimitedMemory : public ValueSerializerTest {
 protected:
// GMock doesn't use the "override" keyword.
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winconsistent-missing-override"
#endif

  class SerializerDelegate : public ValueSerializer::Delegate {
   public:
    explicit SerializerDelegate(ValueSerializerTestWithLimitedMemory* test)
        : test_(test) {}

    ~SerializerDelegate() { EXPECT_EQ(nullptr, last_buffer_); }

    void SetMemoryLimit(size_t limit) { memory_limit_ = limit; }

    void* ReallocateBufferMemory(void* old_buffer, size_t size,
                                 size_t* actual_size) override {
      EXPECT_EQ(old_buffer, last_buffer_);
      if (size > memory_limit_) return nullptr;
      *actual_size = size;
      last_buffer_ = realloc(old_buffer, size);
      return last_buffer_;
    }

    void FreeBufferMemory(void* buffer) override {
      EXPECT_EQ(buffer, last_buffer_);
      last_buffer_ = nullptr;
      free(buffer);
    }

    void ThrowDataCloneError(Local<String> message) override {
      test_->isolate()->ThrowException(Exception::Error(message));
    }

2782 2783
    MOCK_METHOD(Maybe<bool>, WriteHostObject, (Isolate*, Local<Object> object),
                (override));
2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829

   private:
    ValueSerializerTestWithLimitedMemory* test_;
    void* last_buffer_ = nullptr;
    size_t memory_limit_ = 0;
  };

#if __clang__
#pragma clang diagnostic pop
#endif

  ValueSerializer::Delegate* GetSerializerDelegate() override {
    return &serializer_delegate_;
  }

  void BeforeEncode(ValueSerializer* serializer) override {
    serializer_ = serializer;
  }

  SerializerDelegate serializer_delegate_{this};
  ValueSerializer* serializer_ = nullptr;
};

TEST_F(ValueSerializerTestWithLimitedMemory, FailIfNoMemoryInWriteHostObject) {
  EXPECT_CALL(serializer_delegate_, WriteHostObject(isolate(), _))
      .WillRepeatedly(Invoke([this](Isolate*, Local<Object>) {
        static const char kDummyData[1024] = {};
        serializer_->WriteRawBytes(&kDummyData, sizeof(kDummyData));
        return Just(true);
      }));

  // If there is enough memory, things work.
  serializer_delegate_.SetMemoryLimit(2048);
  EncodeTest("new ExampleHostObject()");

  // If not, we get a graceful failure, rather than silent misbehavior.
  serializer_delegate_.SetMemoryLimit(1024);
  InvalidEncodeTest("new ExampleHostObject()");

  // And we definitely don't continue to serialize other things.
  serializer_delegate_.SetMemoryLimit(1024);
  EvaluateScriptForInput("gotA = false");
  InvalidEncodeTest("[new ExampleHostObject, {get a() { gotA = true; }}]");
  EXPECT_TRUE(EvaluateScriptForInput("gotA")->IsFalse());
}

2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892
// We only have basic tests and tests for .stack here, because we have more
// comprehensive tests as web platform tests.
TEST_F(ValueSerializerTest, RoundTripError) {
  Local<Value> value = RoundTripTest("Error('hello')");
  ASSERT_TRUE(value->IsObject());
  Local<Object> error = value.As<Object>();

  Local<Value> name;
  Local<Value> message;

  {
    Context::Scope scope(deserialization_context());
    EXPECT_EQ(error->GetPrototype(), Exception::Error(String::Empty(isolate()))
                                         .As<Object>()
                                         ->GetPrototype());
  }
  ASSERT_TRUE(error->Get(deserialization_context(), StringFromUtf8("name"))
                  .ToLocal(&name));
  ASSERT_TRUE(name->IsString());
  EXPECT_EQ(Utf8Value(name), "Error");

  ASSERT_TRUE(error->Get(deserialization_context(), StringFromUtf8("message"))
                  .ToLocal(&message));
  ASSERT_TRUE(message->IsString());
  EXPECT_EQ(Utf8Value(message), "hello");
}

TEST_F(ValueSerializerTest, DefaultErrorStack) {
  Local<Value> value =
      RoundTripTest("function hkalkcow() { return Error(); } hkalkcow();");
  ASSERT_TRUE(value->IsObject());
  Local<Object> error = value.As<Object>();

  Local<Value> stack;
  ASSERT_TRUE(error->Get(deserialization_context(), StringFromUtf8("stack"))
                  .ToLocal(&stack));
  ASSERT_TRUE(stack->IsString());
  EXPECT_NE(Utf8Value(stack).find("hkalkcow"), std::string::npos);
}

TEST_F(ValueSerializerTest, ModifiedErrorStack) {
  Local<Value> value = RoundTripTest("let e = Error(); e.stack = 'hello'; e");
  ASSERT_TRUE(value->IsObject());
  Local<Object> error = value.As<Object>();

  Local<Value> stack;
  ASSERT_TRUE(error->Get(deserialization_context(), StringFromUtf8("stack"))
                  .ToLocal(&stack));
  ASSERT_TRUE(stack->IsString());
  EXPECT_EQ(Utf8Value(stack), "hello");
}

TEST_F(ValueSerializerTest, NonStringErrorStack) {
  Local<Value> value = RoundTripTest("let e = Error(); e.stack = 17; e");
  ASSERT_TRUE(value->IsObject());
  Local<Object> error = value.As<Object>();

  Local<Value> stack;
  ASSERT_TRUE(error->Get(deserialization_context(), StringFromUtf8("stack"))
                  .ToLocal(&stack));
  EXPECT_TRUE(stack->IsUndefined());
}

2893 2894
}  // namespace
}  // namespace v8