value-serializer-unittest.cc 116 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
#include "src/wasm/wasm-objects.h"
16
#include "test/unittests/test-utils.h"
17
#include "testing/gmock/include/gmock/gmock.h"
18 19 20 21 22
#include "testing/gtest/include/gtest/gtest.h"

namespace v8 {
namespace {

23 24
using ::testing::_;
using ::testing::Invoke;
25
using ::testing::Return;
26

27 28 29 30
class ValueSerializerTest : public TestWithIsolate {
 protected:
  ValueSerializerTest()
      : serialization_context_(Context::New(isolate())),
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
        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;
59 60 61
    isolate_ = reinterpret_cast<i::Isolate*>(isolate());
  }

62
  ~ValueSerializerTest() override {
63 64 65 66 67 68 69
    // 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();
    }
70
  }
71 72 73 74 75 76 77 78

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

79 80 81
  bool ExpectInlineWasm() const { return expect_inline_wasm_; }
  void SetExpectInlineWasm(bool value) { expect_inline_wasm_ = value; }

82
  // Overridden in more specific fixtures.
83
  virtual ValueSerializer::Delegate* GetSerializerDelegate() { return nullptr; }
84
  virtual void BeforeEncode(ValueSerializer*) {}
85 86 87
  virtual ValueDeserializer::Delegate* GetDeserializerDelegate() {
    return nullptr;
  }
88 89
  virtual void BeforeDecode(ValueDeserializer*) {}

90 91 92
  Local<Value> RoundTripTest(Local<Value> input_value) {
    std::vector<uint8_t> encoded = EncodeTest(input_value);
    return DecodeTest(encoded);
93 94
  }

95 96
  // Variant for the common case where a script is used to build the original
  // value.
97 98
  Local<Value> RoundTripTest(const char* source) {
    return RoundTripTest(EvaluateScriptForInput(source));
99 100
  }

101 102
  // Variant which uses JSON.parse/stringify to check the result.
  void RoundTripJSON(const char* source) {
103 104 105 106 107 108 109 110
    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()));
111 112
  }

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

130
  std::vector<uint8_t> EncodeTest(Local<Value> input_value) {
131 132
    Context::Scope scope(serialization_context());
    TryCatch try_catch(isolate());
133
    std::vector<uint8_t> buffer;
134 135 136 137 138 139 140 141 142
    // 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;
143 144
  }

145 146 147 148
  std::vector<uint8_t> EncodeTest(const char* source) {
    return EncodeTest(EvaluateScriptForInput(source));
  }

149
  v8::Local<v8::Message> InvalidEncodeTest(Local<Value> input_value) {
150 151
    Context::Scope scope(serialization_context());
    TryCatch try_catch(isolate());
152 153
    CHECK(DoEncode(input_value).IsNothing());
    return try_catch.Message();
154 155
  }

156 157
  v8::Local<v8::Message> InvalidEncodeTest(const char* source) {
    return InvalidEncodeTest(EvaluateScriptForInput(source));
158 159
  }

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

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

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

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

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

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

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

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

260 261 262 263 264 265 266
  Local<Object> NewDummyUint8Array() {
    static uint8_t data[] = {4, 5, 6};
    Local<ArrayBuffer> ab =
        ArrayBuffer::New(isolate(), static_cast<void*>(data), sizeof(data));
    return Uint8Array::New(ab, 0, sizeof(data));
  }

267 268 269
 private:
  Local<Context> serialization_context_;
  Local<Context> deserialization_context_;
270
  Local<FunctionTemplate> host_object_constructor_template_;
271
  i::Isolate* isolate_;
272
  bool expect_inline_wasm_ = false;
273 274 275 276 277 278

  DISALLOW_COPY_AND_ASSIGN(ValueSerializerTest);
};

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

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

TEST_F(ValueSerializerTest, DecodeOddball) {
  // What this code is expected to generate.
299 300 301 302 303 304 305 306
  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());
307 308

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

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

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
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);
}

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

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

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

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

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

457 458
#if defined(V8_TARGET_LITTLE_ENDIAN)
  // IEEE 754 doubles, little-endian byte order
459 460 461 462 463
  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());

464
  // quiet NaN
465 466 467 468 469
  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()));

470
  // signaling NaN
471 472 473 474
  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()));
475 476 477 478
#endif
  // TODO(jbroman): Equivalent test for big-endian machines.
}

479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
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");
}

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

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

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

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

TEST_F(ValueSerializerTest, DecodeString) {
  // Decoding the strings above from UTF-8.
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
  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));
595

596
  // And from Latin-1 (for the ones that fit).
597 598 599 600 601 602 603 604 605 606 607 608 609
  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));
610

611 612
// And from two-byte strings (endianness dependent).
#if defined(V8_TARGET_LITTLE_ENDIAN)
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
  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));
633 634 635 636 637 638
#endif
  // TODO(jbroman): The same for big-endian systems.
}

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

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

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

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

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

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

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

TEST_F(ValueSerializerTest, DecodeDictionaryObject) {
  // Empty object.
721 722 723 724 725 726
  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");

727
  // String key.
728 729 730 731 732 733 734
  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");

735
  // Integer key (treated as a string, but may be encoded differently).
736 737 738 739 740 741 742
  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");

743
  // Key order must be preserved.
744 745 746 747 748 749
  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'");

750
  // A harder case of enumeration order.
751 752 753 754 755 756 757 758 759 760 761 762 763 764
  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");

765 766 767
  // 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.
768 769 770 771 772
  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");
773 774
}

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

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

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

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

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

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

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

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

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

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

853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
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}]");
}

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

885
  // String key.
886 887 888 889 890 891 892 893
  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");

894
  // Integer key (treated as a string, but may be encoded differently).
895 896 897 898 899 900 901
  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");

902
  // Key order must be preserved.
903 904 905 906 907
  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'");

908
  // A property and an element.
909 910 911 912 913
  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");
914 915
}

916 917
TEST_F(ValueSerializerTest, RoundTripArray) {
  // A simple array of integers.
918 919 920 921 922 923
  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'");

924
  // A long (sparse) array.
925 926 927 928 929
  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");

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

936
  // Duplicate reference in a sparse array.
937 938 939 940 941 942
  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]");

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

949
  // Self reference in a sparse array.
950 951 952 953 954
  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");

955
  // Array with additional properties.
956 957 958 959 960 961
  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'");

962
  // Sparse array with additional properties.
963 964 965 966 967 968
  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'");

969
  // The distinction between holes and undefined elements must be maintained.
970 971 972 973 974 975 976
  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)");
977 978 979 980
}

TEST_F(ValueSerializerTest, DecodeArray) {
  // A simple array of integers.
981 982 983 984 985 986 987 988 989
  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'");

990
  // A long (sparse) array.
991 992 993 994 995 996 997
  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");

998
  // Duplicate reference.
999 1000 1001 1002 1003 1004
  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]");

1005
  // Duplicate reference in a sparse array.
1006 1007 1008 1009 1010 1011 1012 1013 1014
  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]");

1015
  // Self reference.
1016 1017 1018 1019 1020 1021
  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");

1022
  // Self reference in a sparse array.
1023 1024 1025 1026 1027 1028 1029
  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");

1030
  // Array with additional properties.
1031 1032 1033 1034 1035 1036 1037 1038 1039
  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'");

1040
  // Sparse array with additional properties.
1041 1042 1043 1044 1045 1046 1047 1048
  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'");

1049 1050 1051
  // 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.
1052 1053 1054 1055 1056 1057 1058 1059
  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)");
1060 1061
}

1062 1063 1064
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).
1065
  InvalidDecodeTest({0xFF, 0x09, 0x41, 0x80, 0x80, 0x80, 0x80, 0x04});
1066
  // Not so large, but there isn't enough data left in the buffer.
1067
  InvalidDecodeTest({0xFF, 0x09, 0x41, 0x01});
1068 1069
}

1070 1071 1072 1073
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.
1074 1075 1076 1077 1078 1079 1080
  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')");
1081 1082 1083 1084
}

TEST_F(ValueSerializerTest, RoundTripArrayWithTrickyGetters) {
  // If an element is deleted before it is serialized, then it's deleted.
1085 1086 1087 1088 1089 1090 1091
  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)");

1092
  // Same for sparse arrays.
1093 1094 1095 1096 1097 1098 1099 1100 1101
  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)");

1102 1103
  // If the length is changed, then the resulting array still has the original
  // length, but elements that were not yet serialized are gone.
1104 1105 1106 1107 1108 1109
  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)");

1110 1111
  // The same is true if the length is shortened, but there are still items
  // remaining.
1112 1113 1114 1115 1116 1117
  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)");

1118
  // Same for sparse arrays.
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
  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)");

1137 1138
  // If a getter makes a property non-enumerable, it should still be enumerated
  // as enumeration happens once before getters are invoked.
1139 1140 1141 1142 1143 1144 1145 1146 1147
  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");

1148
  // Same for sparse arrays.
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
  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");

1159
  // Getters on the array itself must also run.
1160 1161 1162 1163 1164 1165 1166 1167
  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");

1168
  // Same for sparse arrays.
1169 1170 1171 1172 1173 1174 1175 1176 1177
  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");

1178
  // Even with a getter that deletes things, we don't read from the prototype.
1179 1180 1181 1182 1183 1184 1185 1186
  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)");

1187
  // Same for sparse arrays.
1188 1189 1190 1191 1192 1193 1194 1195
  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)");
1196 1197
}

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

1204
  // Sparse array with a mixture of elements and properties.
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
  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");

1216
  // Sparse array in a sparse array (sanity check of nesting).
1217 1218 1219 1220 1221 1222 1223 1224
  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");
1225 1226
}

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

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.
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
  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)");
1250 1251
}

1252
TEST_F(ValueSerializerTest, RoundTripDate) {
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
  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");
1269 1270 1271
}

TEST_F(ValueSerializerTest, DecodeDate) {
1272
  Local<Value> value;
1273
#if defined(V8_TARGET_LITTLE_ENDIAN)
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
  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()));
1289
#else
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
  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()));
1305
#endif
1306 1307 1308 1309 1310 1311
  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");
1312 1313
}

1314
TEST_F(ValueSerializerTest, RoundTripValueObjects) {
1315 1316 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
  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");
1353 1354 1355 1356 1357 1358 1359 1360
}

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

TEST_F(ValueSerializerTest, DecodeValueObjects) {
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
  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");

1375
#if defined(V8_TARGET_LITTLE_ENDIAN)
1376 1377 1378 1379 1380 1381 1382 1383 1384
  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())");
1385
#else
1386 1387 1388 1389 1390 1391 1392 1393 1394
  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())");
1395
#endif
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
  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");
1420 1421

  // String object containing a Latin-1 string.
1422 1423 1424 1425 1426
  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");
1427 1428
}

1429
TEST_F(ValueSerializerTest, RoundTripRegExp) {
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
  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");
1446 1447 1448
}

TEST_F(ValueSerializerTest, DecodeRegExp) {
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
  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");
1471 1472

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

1479
// Tests that invalid flags are not accepted by the deserializer.
1480
TEST_F(ValueSerializerTest, DecodeRegExpDotAll) {
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
  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'");

1493
  InvalidDecodeTest(
1494
      {0xFF, 0x09, 0x3F, 0x00, 0x52, 0x03, 0x66, 0x6F, 0x6F, 0x7F});
1495 1496
}

1497
TEST_F(ValueSerializerTest, RoundTripMap) {
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
  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");

1509
  // Iteration order must be preserved.
1510 1511 1512 1513 1514 1515
  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'");
1516 1517 1518
}

TEST_F(ValueSerializerTest, DecodeMap) {
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
  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");

1533
  // Iteration order must be preserved.
1534 1535 1536 1537 1538 1539 1540
  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'");
1541 1542 1543 1544 1545
}

TEST_F(ValueSerializerTest, RoundTripMapWithTrickyGetters) {
  // Even if an entry is removed or reassigned, the original key/value pair is
  // used.
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558
  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'");

1559
  // However, deeper modifications of objects yet to be serialized still apply.
1560 1561 1562 1563 1564 1565 1566 1567 1568
  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'");
1569 1570 1571
}

TEST_F(ValueSerializerTest, RoundTripSet) {
1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
  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)");

1585
  // Iteration order must be preserved.
1586 1587 1588 1589 1590 1591
  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'");
1592 1593 1594
}

TEST_F(ValueSerializerTest, DecodeSet) {
1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
  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)");

1610
  // Iteration order must be preserved.
1611 1612 1613 1614 1615
  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'");
1616 1617 1618 1619 1620
}

TEST_F(ValueSerializerTest, RoundTripSetWithTrickyGetters) {
  // Even if an element is added or removed during serialization, the original
  // set of elements is used.
1621 1622 1623 1624 1625 1626 1627 1628 1629
  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'");

1630
  // However, deeper modifications of objects yet to be serialized still apply.
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
  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'");
1641 1642
}

1643
TEST_F(ValueSerializerTest, RoundTripArrayBuffer) {
1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
  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");
1658 1659 1660
}

TEST_F(ValueSerializerTest, DecodeArrayBuffer) {
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
  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");
1677 1678 1679
}

TEST_F(ValueSerializerTest, DecodeInvalidArrayBuffer) {
1680
  InvalidDecodeTest({0xFF, 0x09, 0x42, 0xFF, 0xFF, 0x00});
1681 1682
}

1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697
// 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);
1698 1699 1700 1701 1702 1703 1704
  {
    Isolate::Scope isolate_scope(isolate);
    HandleScope handle_scope(isolate);
    Local<Context> context = Context::New(isolate);
    Context::Scope context_scope(context);
    TryCatch try_catch(isolate);

1705 1706
    const std::vector<uint8_t> data = {0xFF, 0x09, 0x3F, 0x00, 0x42,
                                       0x03, 0x00, 0x80, 0xFF, 0x00};
1707 1708 1709 1710 1711 1712 1713 1714 1715
    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();
1716 1717
}

1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
// 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());
      input_buffer_ = ArrayBuffer::New(isolate(), nullptr, 0);
    }
    {
      Context::Scope scope(deserialization_context());
      output_buffer_ = ArrayBuffer::New(isolate(), kTestByteLength);
1732
      const uint8_t data[kTestByteLength] = {0x00, 0x01, 0x80, 0xFF};
1733
      memcpy(output_buffer_->GetBackingStore()->Data(), data, kTestByteLength);
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
    }
  }

  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) {
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
  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'");
1777 1778
}

1779
TEST_F(ValueSerializerTest, RoundTripTypedArray) {
1780 1781 1782
  // Check that the right type comes out the other side for every kind of typed
  // array.
  Local<Value> value;
1783 1784 1785 1786 1787 1788
#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            \
1789 1790
                   "Array.prototype");

1791
  TYPED_ARRAYS(TYPED_ARRAY_ROUND_TRIP_TEST)
1792
#undef TYPED_ARRAY_ROUND_TRIP_TEST
1793 1794

  // Check that values of various kinds are suitably preserved.
1795 1796 1797 1798 1799 1800 1801 1802
  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'");
1803 1804 1805

  // Array buffer views sharing a buffer should do so on the other side.
  // Similarly, multiple references to the same typed array should be resolved.
1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
  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");
1820 1821 1822 1823 1824
}

TEST_F(ValueSerializerTest, DecodeTypedArray) {
  // Check that the right type comes out the other side for every kind of typed
  // array.
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
  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");

1839
#if defined(V8_TARGET_LITTLE_ENDIAN)
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886
  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");

1887 1888 1889
#endif  // V8_TARGET_LITTLE_ENDIAN

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

1894
#if defined(V8_TARGET_LITTLE_ENDIAN)
1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
  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'");

1905 1906 1907 1908
#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.
1909
  value = DecodeTest(
1910 1911
      {0xFF, 0x09, 0x3F, 0x00, 0x6F, 0x3F, 0x01, 0x53, 0x02, 0x75, 0x38, 0x3F,
       0x01, 0x3F, 0x01, 0x42, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1912 1913
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1914 1915 1916
       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,
1917 1918 1919 1920 1921 1922 1923
       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");
1924 1925 1926 1927 1928
}

TEST_F(ValueSerializerTest, DecodeInvalidTypedArray) {
  // Byte offset out of range.
  InvalidDecodeTest(
1929
      {0xFF, 0x09, 0x42, 0x02, 0x00, 0x00, 0x56, 0x42, 0x03, 0x01});
1930 1931
  // Byte offset in range, offset + length out of range.
  InvalidDecodeTest(
1932
      {0xFF, 0x09, 0x42, 0x02, 0x00, 0x00, 0x56, 0x42, 0x01, 0x03});
1933 1934
  // Byte offset not divisible by element size.
  InvalidDecodeTest(
1935
      {0xFF, 0x09, 0x42, 0x04, 0x00, 0x00, 0x00, 0x00, 0x56, 0x77, 0x01, 0x02});
1936 1937
  // Byte length not divisible by element size.
  InvalidDecodeTest(
1938 1939
      {0xFF, 0x09, 0x42, 0x04, 0x00, 0x00, 0x00, 0x00, 0x56, 0x77, 0x02, 0x01});
  // Invalid view type (0xFF).
1940
  InvalidDecodeTest(
1941
      {0xFF, 0x09, 0x42, 0x02, 0x00, 0x00, 0x56, 0xFF, 0x01, 0x01});
1942 1943 1944
}

TEST_F(ValueSerializerTest, RoundTripDataView) {
1945 1946 1947 1948 1949 1950
  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");
1951 1952 1953
}

TEST_F(ValueSerializerTest, DecodeDataView) {
1954 1955 1956 1957 1958 1959 1960 1961
  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");
1962 1963
}

1964
TEST_F(ValueSerializerTest, DecodeArrayWithLengthProperty1) {
1965 1966 1967
  InvalidDecodeTest({0xff, 0x0d, 0x41, 0x03, 0x49, 0x02, 0x49, 0x04,
                     0x49, 0x06, 0x22, 0x06, 0x6c, 0x65, 0x6e, 0x67,
                     0x74, 0x68, 0x49, 0x02, 0x24, 0x01, 0x03});
1968 1969 1970
}

TEST_F(ValueSerializerTest, DecodeArrayWithLengthProperty2) {
1971 1972 1973
  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});
1974 1975
}

1976 1977 1978
TEST_F(ValueSerializerTest, DecodeInvalidDataView) {
  // Byte offset out of range.
  InvalidDecodeTest(
1979
      {0xFF, 0x09, 0x42, 0x02, 0x00, 0x00, 0x56, 0x3F, 0x03, 0x01});
1980 1981
  // Byte offset in range, offset + length out of range.
  InvalidDecodeTest(
1982
      {0xFF, 0x09, 0x42, 0x02, 0x00, 0x00, 0x56, 0x3F, 0x01, 0x03});
1983 1984
}

1985
class ValueSerializerTestWithSharedArrayBufferClone
1986 1987
    : public ValueSerializerTest {
 protected:
1988 1989
  ValueSerializerTestWithSharedArrayBufferClone()
      : serializer_delegate_(this), deserializer_delegate_(this) {}
1990

1991
  void InitializeData(const std::vector<uint8_t>& data, bool is_wasm_memory) {
1992
    data_ = data;
1993 1994 1995
    {
      Context::Scope scope(serialization_context());
      input_buffer_ =
1996
          NewSharedArrayBuffer(data_.data(), data_.size(), is_wasm_memory);
1997 1998 1999 2000
    }
    {
      Context::Scope scope(deserialization_context());
      output_buffer_ =
2001
          NewSharedArrayBuffer(data_.data(), data_.size(), is_wasm_memory);
2002 2003 2004 2005 2006 2007
    }
  }

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

2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
  Local<SharedArrayBuffer> NewSharedArrayBuffer(void* data, size_t byte_length,
                                                bool is_wasm_memory) {
    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 =
2021 2022
          i_isolate->factory()->NewJSSharedArrayBuffer(
              std::move(backing_store));
2023 2024 2025 2026 2027 2028
      return Utils::ToLocalShared(buffer);
    } else {
      return SharedArrayBuffer::New(isolate(), data, byte_length);
    }
  }

2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
  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;
  }

2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
 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(
2051
        ValueSerializerTestWithSharedArrayBufferClone* test)
2052 2053 2054 2055
        : test_(test) {}
    MOCK_METHOD2(GetSharedArrayBufferId,
                 Maybe<uint32_t>(Isolate* isolate,
                                 Local<SharedArrayBuffer> shared_array_buffer));
2056 2057
    MOCK_METHOD2(GetSharedArrayBufferFromId,
                 MaybeLocal<SharedArrayBuffer>(Isolate* isolate, uint32_t id));
2058 2059 2060 2061 2062
    void ThrowDataCloneError(Local<String> message) override {
      test_->isolate()->ThrowException(Exception::Error(message));
    }

   private:
2063 2064 2065 2066 2067 2068 2069 2070 2071
    ValueSerializerTestWithSharedArrayBufferClone* test_;
  };

  class DeserializerDelegate : public ValueDeserializer::Delegate {
   public:
    explicit DeserializerDelegate(
        ValueSerializerTestWithSharedArrayBufferClone* test) {}
    MOCK_METHOD2(GetSharedArrayBufferFromId,
                 MaybeLocal<SharedArrayBuffer>(Isolate* isolate, uint32_t id));
2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
  };

#if __clang__
#pragma clang diagnostic pop
#endif

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

2082 2083 2084 2085
  ValueDeserializer::Delegate* GetDeserializerDelegate() override {
    return &deserializer_delegate_;
  }

2086
  SerializerDelegate serializer_delegate_;
2087
  DeserializerDelegate deserializer_delegate_;
2088

2089 2090
 private:
  static bool flag_was_enabled_;
2091
  std::vector<uint8_t> data_;
2092 2093 2094 2095
  Local<SharedArrayBuffer> input_buffer_;
  Local<SharedArrayBuffer> output_buffer_;
};

2096
bool ValueSerializerTestWithSharedArrayBufferClone::flag_was_enabled_ = false;
2097

2098 2099
TEST_F(ValueSerializerTestWithSharedArrayBufferClone,
       RoundTripSharedArrayBufferClone) {
2100
  InitializeData({0x00, 0x01, 0x80, 0xFF}, false);
2101

2102 2103 2104
  EXPECT_CALL(serializer_delegate_,
              GetSharedArrayBufferId(isolate(), input_buffer()))
      .WillRepeatedly(Return(Just(0U)));
2105 2106
  EXPECT_CALL(deserializer_delegate_, GetSharedArrayBufferFromId(isolate(), 0U))
      .WillRepeatedly(Return(output_buffer()));
2107

2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
  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'");
2130 2131
}

2132
TEST_F(ValueSerializerTestWithSharedArrayBufferClone,
2133 2134 2135 2136
       RoundTripWebAssemblyMemory) {
  bool flag_was_enabled = i::FLAG_experimental_wasm_threads;
  i::FLAG_experimental_wasm_threads = true;

2137
  std::vector<uint8_t> data = {0x00, 0x01, 0x80, 0xFF};
2138
  data.resize(65536);
2139
  InitializeData(data, true);
2140 2141 2142 2143

  EXPECT_CALL(serializer_delegate_,
              GetSharedArrayBufferId(isolate(), input_buffer()))
      .WillRepeatedly(Return(Just(0U)));
2144 2145
  EXPECT_CALL(deserializer_delegate_, GetSharedArrayBufferFromId(isolate(), 0U))
      .WillRepeatedly(Return(output_buffer()));
2146

2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
  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'");
2161 2162 2163 2164

  i::FLAG_experimental_wasm_threads = flag_was_enabled;
}

2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
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) {}
    MOCK_METHOD2(WriteHostObject,
                 Maybe<bool>(Isolate* isolate, Local<Object> object));
    void ThrowDataCloneError(Local<String> message) override {
      test_->isolate()->ThrowException(Exception::Error(message));
    }

   private:
    ValueSerializerTestWithHostObject* test_;
  };

  class DeserializerDelegate : public ValueDeserializer::Delegate {
   public:
    MOCK_METHOD1(ReadHostObject, MaybeLocal<Object>(Isolate* isolate));
  };

#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;
};

2237 2238 2239
// This is a tag that is used in V8. Using this ensures that we have separate
// tag namespaces.
const uint8_t ValueSerializerTestWithHostObject::kExampleHostObjectTag = 'T';
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260

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);
      }));
2261 2262 2263 2264 2265 2266 2267 2268 2269
  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");
2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298
}

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);
      }));
2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309
  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");
2310 2311
}

2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
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);
      }));
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346
  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");
2347 2348
}

2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373
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);
      }));
2374 2375 2376 2377 2378
  Local<Value> value = RoundTripTest("new ExampleHostObject()");
  ASSERT_TRUE(value->IsObject());
  ASSERT_TRUE(Object::Cast(*value)->InternalFieldCount());
  ExpectScriptTrue(
      "Object.getPrototypeOf(result) === ExampleHostObject.prototype");
2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394
}

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);
      }));
2395 2396 2397
  RoundTripTest("({ a: new ExampleHostObject(), get b() { return this.a; }})");
  ExpectScriptTrue("result.a instanceof ExampleHostObject");
  ExpectScriptTrue("result.a === result.b");
2398 2399
}

2400 2401 2402 2403 2404 2405
TEST_F(ValueSerializerTestWithHostObject, DecodeSimpleHostObject) {
  EXPECT_CALL(deserializer_delegate_, ReadHostObject(isolate()))
      .WillRepeatedly(Invoke([this](Isolate*) {
        EXPECT_TRUE(ReadExampleHostObjectTag());
        return NewHostObject(deserialization_context(), 0, nullptr);
      }));
2406 2407 2408
  DecodeTest({0xFF, 0x0D, 0x5C, kExampleHostObjectTag});
  ExpectScriptTrue(
      "Object.getPrototypeOf(result) === ExampleHostObject.prototype");
2409 2410
}

2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
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(
2433 2434 2435 2436
      "({ 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");
2437 2438
}

2439 2440 2441 2442
// 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.

2443 2444 2445 2446 2447 2448 2449 2450
// A simple module which exports an "increment" function.
// Copied from test/mjsunit/wasm/incrementer.wasm.
const unsigned char kIncrementerWasm[] = {
    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,
};

2451
class ValueSerializerTestWithWasm : public ValueSerializerTest {
2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480
 public:
  static const char* kUnsupportedSerialization;

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

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

  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_;
  }

2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493
 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;
  }

2494 2495 2496
  class ThrowingSerializer : public ValueSerializer::Delegate {
   public:
    Maybe<uint32_t> GetWasmModuleTransferId(
2497
        Isolate* isolate, Local<WasmModuleObject> module) override {
2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
      isolate->ThrowException(Exception::Error(
          String::NewFromOneByte(
              isolate,
              reinterpret_cast<const uint8_t*>(kUnsupportedSerialization),
              NewStringType::kNormal)
              .ToLocalChecked()));
      return Nothing<uint32_t>();
    }

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

  class SerializeToTransfer : public ValueSerializer::Delegate {
   public:
2512
    explicit SerializeToTransfer(std::vector<CompiledWasmModule>* modules)
2513 2514
        : modules_(modules) {}
    Maybe<uint32_t> GetWasmModuleTransferId(
2515
        Isolate* isolate, Local<WasmModuleObject> module) override {
2516
      modules_->push_back(module->GetCompiledModule());
2517 2518 2519 2520 2521 2522
      return Just(static_cast<uint32_t>(modules_->size()) - 1);
    }

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

   private:
2523
    std::vector<CompiledWasmModule>* modules_;
2524 2525 2526 2527
  };

  class DeserializeFromTransfer : public ValueDeserializer::Delegate {
   public:
2528
    explicit DeserializeFromTransfer(std::vector<CompiledWasmModule>* modules)
2529 2530
        : modules_(modules) {}

2531 2532
    MaybeLocal<WasmModuleObject> GetWasmModuleFromId(Isolate* isolate,
                                                     uint32_t id) override {
2533
      return WasmModuleObject::FromCompiledModule(isolate, modules_->at(id));
2534 2535 2536
    }

   private:
2537
    std::vector<CompiledWasmModule>* modules_;
2538 2539 2540 2541 2542 2543 2544 2545 2546 2547
  };

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

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

2548
  Local<WasmModuleObject> MakeWasm() {
2549
    Context::Scope scope(serialization_context());
2550
    return WasmModuleObject::DeserializeOrCompile(
2551 2552 2553 2554 2555 2556
               isolate(), {nullptr, 0},
               {kIncrementerWasm, sizeof(kIncrementerWasm)})
        .ToLocalChecked();
  }

  void ExpectPass() {
2557 2558 2559 2560 2561
    Local<Value> value = RoundTripTest(MakeWasm());
    Context::Scope scope(deserialization_context());
    ASSERT_TRUE(value->IsWebAssemblyCompiledModule());
    ExpectScriptTrue(
        "new WebAssembly.Instance(result).exports.increment(8) === 9");
2562 2563 2564
  }

  void ExpectFail() {
2565 2566
    const std::vector<uint8_t> data = EncodeTest(MakeWasm());
    InvalidDecodeTest(data);
2567 2568 2569
  }

  Local<Value> GetComplexObjectWithDuplicate() {
2570
    Context::Scope scope(serialization_context());
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586
    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());
2587 2588 2589
    ExpectScriptTrue("result.mod1 instanceof WebAssembly.Module");
    ExpectScriptTrue("result.mod2 instanceof WebAssembly.Module");
    ExpectScriptTrue("result.num === 2");
2590 2591 2592
  }

  Local<Value> GetComplexObjectWithMany() {
2593
    Context::Scope scope(serialization_context());
2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614
    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();
  }

2615 2616
 private:
  static bool g_saved_flag;
2617
  std::vector<CompiledWasmModule> transfer_modules_;
2618 2619 2620 2621 2622 2623
  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_;
2624 2625 2626
};

bool ValueSerializerTestWithWasm::g_saved_flag = false;
2627 2628 2629 2630 2631 2632 2633 2634
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();
2635 2636 2637
  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]);
2638 2639
  message->Get()->WriteOneByte(isolate(),
                               reinterpret_cast<uint8_t*>(buff.get()));
2640 2641 2642 2643 2644
  // 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);
2645
}
2646

2647 2648 2649 2650
// The default deserializer throws if wasm transfer is attempted
TEST_F(ValueSerializerTestWithWasm, DefaultDeserializationDelegate) {
  EnableTransferSerialization();
  EnableDefaultDeserializer();
2651
  ExpectFail();
2652
}
mtrofin's avatar
mtrofin committed
2653

2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
// 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, RountripWasmInline) {
  SetExpectInlineWasm(true);
  ExpectPass();
}

TEST_F(ValueSerializerTestWithWasm, CannotDeserializeWasmInlineData) {
  ExpectFail();
}

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

TEST_F(ValueSerializerTestWithWasm, ComplexObjectDuplicateTransfer) {
  EnableTransferSerialization();
  EnableTransferDeserialization();
2686 2687 2688
  Local<Value> value = RoundTripTest(GetComplexObjectWithDuplicate());
  VerifyComplexObject(value);
  ExpectScriptTrue("result.mod1 === result.mod2");
2689 2690 2691 2692
}

TEST_F(ValueSerializerTestWithWasm, ComplexObjectDuplicateInline) {
  SetExpectInlineWasm(true);
2693 2694 2695
  Local<Value> value = RoundTripTest(GetComplexObjectWithDuplicate());
  VerifyComplexObject(value);
  ExpectScriptTrue("result.mod1 === result.mod2");
2696 2697 2698 2699 2700
}

TEST_F(ValueSerializerTestWithWasm, ComplexObjectWithManyTransfer) {
  EnableTransferSerialization();
  EnableTransferDeserialization();
2701 2702 2703
  Local<Value> value = RoundTripTest(GetComplexObjectWithMany());
  VerifyComplexObject(value);
  ExpectScriptTrue("result.mod1 != result.mod2");
2704 2705 2706 2707
}

TEST_F(ValueSerializerTestWithWasm, ComplexObjectWithManyInline) {
  SetExpectInlineWasm(true);
2708 2709 2710
  Local<Value> value = RoundTripTest(GetComplexObjectWithMany());
  VerifyComplexObject(value);
  ExpectScriptTrue("result.mod1 != result.mod2");
2711 2712 2713 2714
}

// As produced around Chrome 56.
const unsigned char kSerializedIncrementerWasm[] = {
2715 2716 2717 2718 2719 2720 2721 2722 2723
    0xFF, 0x09, 0x3F, 0x00, 0x57, 0x79, 0x2D, 0x00, 0x61, 0x73, 0x6D, 0x0D,
    0x00, 0x00, 0x00, 0x01, 0x06, 0x01, 0x60, 0x01, 0x7F, 0x01, 0x7F, 0x03,
    0x02, 0x01, 0x00, 0x07, 0x0D, 0x01, 0x09, 0x69, 0x6E, 0x63, 0x72, 0x65,
    0x6D, 0x65, 0x6E, 0x74, 0x00, 0x00, 0x0A, 0x08, 0x01, 0x06, 0x00, 0x20,
    0x00, 0x41, 0x01, 0x6A, 0xF8, 0x04, 0xA1, 0x06, 0xDE, 0xC0, 0xC6, 0x44,
    0x3C, 0x29, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x02, 0x00, 0x00, 0x81, 0x4E,
    0xCE, 0x7C, 0x05, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x30, 0x02,
    0x00, 0x00, 0xB0, 0x25, 0x30, 0xE3, 0xF2, 0xDB, 0x2E, 0x48, 0x00, 0x00,
    0x00, 0x80, 0xE8, 0x00, 0x00, 0x80, 0xE0, 0x01, 0x00, 0x80, 0x00, 0x00,
2724
    0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x07, 0x08, 0x00, 0x00, 0x09, 0x04,
2725 2726 2727 2728 2729 2730 2731
    0x10, 0x02, 0x00, 0x00, 0x00, 0x00, 0x01, 0x3C, 0x8C, 0xC0, 0x00, 0x00,
    0x00, 0x00, 0x0D, 0x00, 0x00, 0x00, 0x01, 0x10, 0x8C, 0xC0, 0x00, 0x00,
    0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x70, 0x94, 0x01, 0x0C, 0x8B,
    0xC1, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x25, 0xDC, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x9E, 0x01, 0x10, 0x8C, 0xC0, 0x00, 0x00,
    0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x84, 0xC0, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x05, 0x7D, 0x01, 0x1A, 0xE1, 0x02, 0x00, 0x00,
2732 2733
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x23, 0x88, 0x42, 0x32, 0x03,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x00,
2734 2735 2736 2737 2738 2739 2740 2741 2742
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x04, 0x00,
    0x00, 0x02, 0xA1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF,
    0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x49, 0x3B, 0xA5, 0x60, 0x0C, 0x00,
    0x00, 0x0F, 0x86, 0x04, 0x00, 0x00, 0x00, 0x83, 0xC0, 0x01, 0xC3, 0x55,
    0x48, 0x89, 0xE5, 0x49, 0xBA, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00,
    0x00, 0x41, 0x52, 0x48, 0x83, 0xEC, 0x08, 0x48, 0x89, 0x45, 0xF0, 0x48,
    0xBB, 0xB0, 0x67, 0xC6, 0x00, 0x00, 0x00, 0x00, 0x00, 0x33, 0xC0, 0x48,
    0xBE, 0xE1, 0x57, 0x81, 0x85, 0xF6, 0x14, 0x00, 0x00, 0xE8, 0xFC, 0x3C,
    0xEA, 0xFF, 0x48, 0x8B, 0x45, 0xF0, 0x48, 0x8B, 0xE5, 0x5D, 0xEB, 0xBF,
2743
    0x66, 0x90, 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x44, 0x00,
2744
    0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x0F, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
2745 2746
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
2747 2748 2749 2750
    0x00, 0x00, 0x0F, 0x20, 0x84, 0x0F, 0x7D, 0x01, 0x0D, 0x00, 0x0F, 0x04,
    0x6D, 0x08, 0x0F, 0xF0, 0x02, 0x80, 0x94, 0x01, 0x0C, 0x8B, 0xC1, 0x00,
    0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0xED, 0xA9, 0x2D, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x9E, 0xE0, 0x38, 0x1A, 0x61, 0x03, 0x00, 0x00, 0x00,
2751
    0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x23, 0x88, 0x42, 0x32, 0x03, 0x00,
2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9A, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x4E, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
    0x02, 0xF9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF,
    0xFF, 0x00, 0x00, 0x00, 0x00, 0x55, 0x48, 0x89, 0xE5, 0x56, 0x57, 0x48,
    0x8B, 0x45, 0x10, 0xE8, 0x11, 0xED, 0xED, 0xFF, 0xA8, 0x01, 0x0F, 0x85,
    0x2D, 0x00, 0x00, 0x00, 0x48, 0xC1, 0xE8, 0x20, 0xC5, 0xF9, 0x57, 0xC0,
    0xC5, 0xFB, 0x2A, 0xC0, 0xC4, 0xE1, 0xFB, 0x2C, 0xC0, 0x48, 0x83, 0xF8,
    0x01, 0x0F, 0x80, 0x34, 0x00, 0x00, 0x00, 0x8B, 0xC0, 0xE8, 0x27, 0xFE,
    0xFF, 0xFF, 0x48, 0xC1, 0xE0, 0x20, 0x48, 0x8B, 0xE5, 0x5D, 0xC2, 0x10,
    0x00, 0x49, 0x39, 0x45, 0xA0, 0x0F, 0x84, 0x07, 0x00, 0x00, 0x00, 0xC5,
    0xFB, 0x10, 0x40, 0x07, 0xEB, 0xCE, 0x49, 0xBA, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0xF8, 0x7F, 0xC4, 0xC1, 0xF9, 0x6E, 0xC2, 0xEB, 0xBD, 0x48,
    0x83, 0xEC, 0x08, 0xC5, 0xFB, 0x11, 0x04, 0x24, 0xE8, 0xCC, 0xFE, 0xFF,
    0xFF, 0x48, 0x83, 0xC4, 0x08, 0xEB, 0xB8, 0x66, 0x90, 0x02, 0x00, 0x00,
    0x00, 0x03, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF,
    0x0F, 0x39, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0x0F, 0xFF, 0xFF, 0x00,
    0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x20, 0x84,
    0x0F, 0xCC, 0x6E, 0x7D, 0x01, 0x72, 0x98, 0x00, 0x0F, 0xDC, 0x6D, 0x0C,
    0x0F, 0xB0, 0x84, 0x0D, 0x04, 0x84, 0xE3, 0xC0, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x84, 0xE0, 0x84, 0x84, 0x18, 0x2F, 0x2F, 0x2F,
    0x2F, 0x2F};
2773 2774

TEST_F(ValueSerializerTestWithWasm, DecodeWasmModule) {
2775
  if ((true)) return;  // TODO(mtrofin): fix this test
2776 2777 2778
  std::vector<uint8_t> raw(
      kSerializedIncrementerWasm,
      kSerializedIncrementerWasm + sizeof(kSerializedIncrementerWasm));
2779 2780 2781 2782
  Local<Value> value = DecodeTest(raw);
  ASSERT_TRUE(value->IsWebAssemblyCompiledModule());
  ExpectScriptTrue(
      "new WebAssembly.Instance(result).exports.increment(8) === 9");
2783 2784 2785 2786 2787
}

// As above, but with empty compiled data. Should work due to fallback to wire
// data.
const unsigned char kSerializedIncrementerWasmWithInvalidCompiledData[] = {
2788 2789 2790 2791 2792
    0xFF, 0x09, 0x3F, 0x00, 0x57, 0x79, 0x2D, 0x00, 0x61, 0x73, 0x6D,
    0x0D, 0x00, 0x00, 0x00, 0x01, 0x06, 0x01, 0x60, 0x01, 0x7F, 0x01,
    0x7F, 0x03, 0x02, 0x01, 0x00, 0x07, 0x0D, 0x01, 0x09, 0x69, 0x6E,
    0x63, 0x72, 0x65, 0x6D, 0x65, 0x6E, 0x74, 0x00, 0x00, 0x0A, 0x08,
    0x01, 0x06, 0x00, 0x20, 0x00, 0x41, 0x01, 0x6A, 0x00};
2793 2794

TEST_F(ValueSerializerTestWithWasm, DecodeWasmModuleWithInvalidCompiledData) {
2795
  if ((true)) return;  // TODO(titzer): regenerate this test
2796 2797 2798 2799
  std::vector<uint8_t> raw(
      kSerializedIncrementerWasmWithInvalidCompiledData,
      kSerializedIncrementerWasmWithInvalidCompiledData +
          sizeof(kSerializedIncrementerWasmWithInvalidCompiledData));
2800 2801 2802 2803
  Local<Value> value = DecodeTest(raw);
  ASSERT_TRUE(value->IsWebAssemblyCompiledModule());
  ExpectScriptTrue(
      "new WebAssembly.Instance(result).exports.increment(8) === 9");
2804 2805 2806 2807
}

// As above, but also with empty wire data. Should fail.
const unsigned char kSerializedIncrementerWasmInvalid[] = {
2808
    0xFF, 0x09, 0x3F, 0x00, 0x57, 0x79, 0x00, 0x00};
2809 2810 2811 2812 2813 2814 2815 2816 2817 2818

TEST_F(ValueSerializerTestWithWasm,
       DecodeWasmModuleWithInvalidCompiledAndWireData) {
  std::vector<uint8_t> raw(kSerializedIncrementerWasmInvalid,
                           kSerializedIncrementerWasmInvalid +
                               sizeof(kSerializedIncrementerWasmInvalid));
  InvalidDecodeTest(raw);
}

TEST_F(ValueSerializerTestWithWasm, DecodeWasmModuleWithInvalidDataLength) {
2819 2820
  InvalidDecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x57, 0x79, 0x7F, 0x00});
  InvalidDecodeTest({0xFF, 0x09, 0x3F, 0x00, 0x57, 0x79, 0x00, 0x7F});
2821 2822
}

2823 2824 2825 2826 2827 2828 2829 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 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
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));
    }

    MOCK_METHOD2(WriteHostObject,
                 Maybe<bool>(Isolate* isolate, Local<Object> object));

   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());
}

2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969
// 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());
}

2970 2971
}  // namespace
}  // namespace v8