value-serializer-unittest.cc 127 KB
Newer Older
1 2 3 4 5
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

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

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

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

namespace v8 {
namespace {

21 22
using ::testing::_;
using ::testing::Invoke;
23
using ::testing::Return;
24

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

  ~ValueSerializerTest() {
    // 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();
    }
68
  }
69 70 71 72 73 74 75 76

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

77 78 79
  bool ExpectInlineWasm() const { return expect_inline_wasm_; }
  void SetExpectInlineWasm(bool value) { expect_inline_wasm_ = value; }

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

89 90 91
  template <typename InputFunctor, typename OutputFunctor>
  void RoundTripTest(const InputFunctor& input_functor,
                     const OutputFunctor& output_functor) {
92 93 94 95 96 97
    EncodeTest(input_functor,
               [this, &output_functor](const std::vector<uint8_t>& data) {
                 DecodeTest(data, output_functor);
               });
  }

98 99 100 101 102 103 104 105
  // Variant for the common case where a script is used to build the original
  // value.
  template <typename OutputFunctor>
  void RoundTripTest(const char* source, const OutputFunctor& output_functor) {
    RoundTripTest([this, source]() { return EvaluateScriptForInput(source); },
                  output_functor);
  }

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
  // Variant which uses JSON.parse/stringify to check the result.
  void RoundTripJSON(const char* source) {
    RoundTripTest(
        [this, source]() {
          return JSON::Parse(serialization_context_, StringFromUtf8(source))
              .ToLocalChecked();
        },
        [this, source](Local<Value> value) {
          ASSERT_TRUE(value->IsObject());
          EXPECT_EQ(source, Utf8Value(JSON::Stringify(deserialization_context_,
                                                      value.As<Object>())
                                          .ToLocalChecked()));
        });
  }

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

136 137 138 139 140 141
  template <typename InputFunctor, typename EncodedDataFunctor>
  void EncodeTest(const InputFunctor& input_functor,
                  const EncodedDataFunctor& encoded_data_functor) {
    Context::Scope scope(serialization_context());
    TryCatch try_catch(isolate());
    Local<Value> input_value = input_functor();
142 143
    std::vector<uint8_t> buffer;
    ASSERT_TRUE(DoEncode(input_value).To(&buffer));
144
    ASSERT_FALSE(try_catch.HasCaught());
145 146 147
    encoded_data_functor(buffer);
  }

148 149 150
  template <typename InputFunctor, typename MessageFunctor>
  void InvalidEncodeTest(const InputFunctor& input_functor,
                         const MessageFunctor& functor) {
151 152
    Context::Scope scope(serialization_context());
    TryCatch try_catch(isolate());
153
    Local<Value> input_value = input_functor();
154 155
    ASSERT_TRUE(DoEncode(input_value).IsNothing());
    functor(try_catch.Message());
156 157
  }

158 159 160 161 162 163
  template <typename MessageFunctor>
  void InvalidEncodeTest(const char* source, const MessageFunctor& functor) {
    InvalidEncodeTest(
        [this, source]() { return EvaluateScriptForInput(source); }, functor);
  }

164 165 166 167
  void InvalidEncodeTest(const char* source) {
    InvalidEncodeTest(source, [](Local<Message>) {});
  }

168 169 170
  template <typename OutputFunctor>
  void DecodeTest(const std::vector<uint8_t>& data,
                  const OutputFunctor& output_functor) {
171 172
    Local<Context> context = deserialization_context();
    Context::Scope scope(context);
173
    TryCatch try_catch(isolate());
174
    ValueDeserializer deserializer(isolate(), &data[0],
175 176
                                   static_cast<int>(data.size()),
                                   GetDeserializerDelegate());
177
    deserializer.SetSupportsLegacyWireFormat(true);
178
    deserializer.SetExpectInlineWasm(ExpectInlineWasm());
179
    BeforeDecode(&deserializer);
180
    ASSERT_TRUE(deserializer.ReadHeader(context).FromMaybe(false));
181
    Local<Value> result;
182
    ASSERT_TRUE(deserializer.ReadValue(context).ToLocal(&result));
183 184
    ASSERT_FALSE(result.IsEmpty());
    ASSERT_FALSE(try_catch.HasCaught());
185 186 187 188
    ASSERT_TRUE(
        context->Global()
            ->CreateDataProperty(context, StringFromUtf8("result"), result)
            .FromMaybe(false));
189 190 191 192
    output_functor(result);
    ASSERT_FALSE(try_catch.HasCaught());
  }

193 194 195
  template <typename OutputFunctor>
  void DecodeTestForVersion0(const std::vector<uint8_t>& data,
                             const OutputFunctor& output_functor) {
196 197
    Local<Context> context = deserialization_context();
    Context::Scope scope(context);
198
    TryCatch try_catch(isolate());
199
    ValueDeserializer deserializer(isolate(), &data[0],
200 201
                                   static_cast<int>(data.size()),
                                   GetDeserializerDelegate());
202
    deserializer.SetSupportsLegacyWireFormat(true);
203
    deserializer.SetExpectInlineWasm(ExpectInlineWasm());
204
    BeforeDecode(&deserializer);
205
    ASSERT_TRUE(deserializer.ReadHeader(context).FromMaybe(false));
206
    ASSERT_EQ(0u, deserializer.GetWireFormatVersion());
207
    Local<Value> result;
208
    ASSERT_TRUE(deserializer.ReadValue(context).ToLocal(&result));
209 210
    ASSERT_FALSE(result.IsEmpty());
    ASSERT_FALSE(try_catch.HasCaught());
211 212 213 214
    ASSERT_TRUE(
        context->Global()
            ->CreateDataProperty(context, StringFromUtf8("result"), result)
            .FromMaybe(false));
215 216 217 218
    output_functor(result);
    ASSERT_FALSE(try_catch.HasCaught());
  }

219
  void InvalidDecodeTest(const std::vector<uint8_t>& data) {
220 221
    Local<Context> context = deserialization_context();
    Context::Scope scope(context);
222
    TryCatch try_catch(isolate());
223
    ValueDeserializer deserializer(isolate(), &data[0],
224 225
                                   static_cast<int>(data.size()),
                                   GetDeserializerDelegate());
226
    deserializer.SetSupportsLegacyWireFormat(true);
227
    deserializer.SetExpectInlineWasm(ExpectInlineWasm());
228
    BeforeDecode(&deserializer);
229 230 231 232 233
    Maybe<bool> header_result = deserializer.ReadHeader(context);
    if (header_result.IsNothing()) {
      EXPECT_TRUE(try_catch.HasCaught());
      return;
    }
234
    ASSERT_TRUE(header_result.ToChecked());
235
    ASSERT_TRUE(deserializer.ReadValue(context).IsEmpty());
236
    EXPECT_TRUE(try_catch.HasCaught());
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
  }

  Local<Value> EvaluateScriptForInput(const char* utf8_source) {
    Local<String> source = StringFromUtf8(utf8_source);
    Local<Script> script =
        Script::Compile(serialization_context_, source).ToLocalChecked();
    return script->Run(serialization_context_).ToLocalChecked();
  }

  bool EvaluateScriptForResultBool(const char* utf8_source) {
    Local<String> source = StringFromUtf8(utf8_source);
    Local<Script> script =
        Script::Compile(deserialization_context_, source).ToLocalChecked();
    Local<Value> value = script->Run(deserialization_context_).ToLocalChecked();
    return value->BooleanValue(deserialization_context_).FromJust();
  }

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

259 260 261 262 263
  static std::string Utf8Value(Local<Value> value) {
    String::Utf8Value utf8(value);
    return std::string(*utf8, utf8.length());
  }

264 265 266 267 268 269 270 271
  Local<Object> NewHostObject(Local<Context> context, int argc,
                              Local<Value> argv[]) {
    return host_object_constructor_template_->GetFunction(context)
        .ToLocalChecked()
        ->NewInstance(context, argc, argv)
        .ToLocalChecked();
  }

272 273 274 275 276 277 278
  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));
  }

279 280 281
 private:
  Local<Context> serialization_context_;
  Local<Context> deserialization_context_;
282
  Local<FunctionTemplate> host_object_constructor_template_;
283
  i::Isolate* isolate_;
284
  bool expect_inline_wasm_ = false;
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340

  DISALLOW_COPY_AND_ASSIGN(ValueSerializerTest);
};

TEST_F(ValueSerializerTest, DecodeInvalid) {
  // Version tag but no content.
  InvalidDecodeTest({0xff});
  // Version too large.
  InvalidDecodeTest({0xff, 0x7f, 0x5f});
  // Nonsense tag.
  InvalidDecodeTest({0xff, 0x09, 0xdd});
}

TEST_F(ValueSerializerTest, RoundTripOddball) {
  RoundTripTest([this]() { return Undefined(isolate()); },
                [](Local<Value> value) { EXPECT_TRUE(value->IsUndefined()); });
  RoundTripTest([this]() { return True(isolate()); },
                [](Local<Value> value) { EXPECT_TRUE(value->IsTrue()); });
  RoundTripTest([this]() { return False(isolate()); },
                [](Local<Value> value) { EXPECT_TRUE(value->IsFalse()); });
  RoundTripTest([this]() { return Null(isolate()); },
                [](Local<Value> value) { EXPECT_TRUE(value->IsNull()); });
}

TEST_F(ValueSerializerTest, DecodeOddball) {
  // What this code is expected to generate.
  DecodeTest({0xff, 0x09, 0x5f},
             [](Local<Value> value) { EXPECT_TRUE(value->IsUndefined()); });
  DecodeTest({0xff, 0x09, 0x54},
             [](Local<Value> value) { EXPECT_TRUE(value->IsTrue()); });
  DecodeTest({0xff, 0x09, 0x46},
             [](Local<Value> value) { EXPECT_TRUE(value->IsFalse()); });
  DecodeTest({0xff, 0x09, 0x30},
             [](Local<Value> value) { EXPECT_TRUE(value->IsNull()); });

  // What v9 of the Blink code generates.
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x5f, 0x00},
             [](Local<Value> value) { EXPECT_TRUE(value->IsUndefined()); });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x54, 0x00},
             [](Local<Value> value) { EXPECT_TRUE(value->IsTrue()); });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x46, 0x00},
             [](Local<Value> value) { EXPECT_TRUE(value->IsFalse()); });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x30, 0x00},
             [](Local<Value> value) { EXPECT_TRUE(value->IsNull()); });

  // v0 (with no explicit version).
  DecodeTest({0x5f, 0x00},
             [](Local<Value> value) { EXPECT_TRUE(value->IsUndefined()); });
  DecodeTest({0x54, 0x00},
             [](Local<Value> value) { EXPECT_TRUE(value->IsTrue()); });
  DecodeTest({0x46, 0x00},
             [](Local<Value> value) { EXPECT_TRUE(value->IsFalse()); });
  DecodeTest({0x30, 0x00},
             [](Local<Value> value) { EXPECT_TRUE(value->IsNull()); });
}

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
TEST_F(ValueSerializerTest, RoundTripNumber) {
  RoundTripTest([this]() { return Integer::New(isolate(), 42); },
                [](Local<Value> value) {
                  ASSERT_TRUE(value->IsInt32());
                  EXPECT_EQ(42, Int32::Cast(*value)->Value());
                });
  RoundTripTest([this]() { return Integer::New(isolate(), -31337); },
                [](Local<Value> value) {
                  ASSERT_TRUE(value->IsInt32());
                  EXPECT_EQ(-31337, Int32::Cast(*value)->Value());
                });
  RoundTripTest(
      [this]() {
        return Integer::New(isolate(), std::numeric_limits<int32_t>::min());
      },
      [](Local<Value> value) {
        ASSERT_TRUE(value->IsInt32());
        EXPECT_EQ(std::numeric_limits<int32_t>::min(),
                  Int32::Cast(*value)->Value());
      });
  RoundTripTest([this]() { return Number::New(isolate(), -0.25); },
                [](Local<Value> value) {
                  ASSERT_TRUE(value->IsNumber());
                  EXPECT_EQ(-0.25, Number::Cast(*value)->Value());
                });
  RoundTripTest(
      [this]() {
        return Number::New(isolate(), std::numeric_limits<double>::quiet_NaN());
      },
      [](Local<Value> value) {
        ASSERT_TRUE(value->IsNumber());
        EXPECT_TRUE(std::isnan(Number::Cast(*value)->Value()));
      });
}

TEST_F(ValueSerializerTest, DecodeNumber) {
  // 42 zig-zag encoded (signed)
  DecodeTest({0xff, 0x09, 0x49, 0x54},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsInt32());
               EXPECT_EQ(42, Int32::Cast(*value)->Value());
             });
  // 42 varint encoded (unsigned)
  DecodeTest({0xff, 0x09, 0x55, 0x2a},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsInt32());
               EXPECT_EQ(42, Int32::Cast(*value)->Value());
             });
  // 160 zig-zag encoded (signed)
  DecodeTest({0xff, 0x09, 0x49, 0xc0, 0x02},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsInt32());
               ASSERT_EQ(160, Int32::Cast(*value)->Value());
             });
  // 160 varint encoded (unsigned)
  DecodeTest({0xff, 0x09, 0x55, 0xa0, 0x01},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsInt32());
               ASSERT_EQ(160, Int32::Cast(*value)->Value());
             });
#if defined(V8_TARGET_LITTLE_ENDIAN)
  // IEEE 754 doubles, little-endian byte order
  DecodeTest({0xff, 0x09, 0x4e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0xbf},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsNumber());
               EXPECT_EQ(-0.25, Number::Cast(*value)->Value());
             });
  // quiet NaN
  DecodeTest({0xff, 0x09, 0x4e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x7f},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsNumber());
               EXPECT_TRUE(std::isnan(Number::Cast(*value)->Value()));
             });
  // signaling NaN
  DecodeTest({0xff, 0x09, 0x4e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf4, 0x7f},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsNumber());
               EXPECT_TRUE(std::isnan(Number::Cast(*value)->Value()));
             });
#endif
  // TODO(jbroman): Equivalent test for big-endian machines.
}

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
// 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) {
  RoundTripTest([this]() { return String::Empty(isolate()); },
                [](Local<Value> value) {
                  ASSERT_TRUE(value->IsString());
                  EXPECT_EQ(0, String::Cast(*value)->Length());
                });
  // Inside ASCII.
  RoundTripTest([this]() { return StringFromUtf8(kHelloString); },
                [](Local<Value> value) {
                  ASSERT_TRUE(value->IsString());
                  EXPECT_EQ(5, String::Cast(*value)->Length());
                  EXPECT_EQ(kHelloString, Utf8Value(value));
                });
  // Inside Latin-1 (i.e. one-byte string), but not ASCII.
  RoundTripTest([this]() { return StringFromUtf8(kQuebecString); },
                [](Local<Value> value) {
                  ASSERT_TRUE(value->IsString());
                  EXPECT_EQ(6, String::Cast(*value)->Length());
                  EXPECT_EQ(kQuebecString, Utf8Value(value));
                });
  // An emoji (decodes to two 16-bit chars).
  RoundTripTest([this]() { return StringFromUtf8(kEmojiString); },
                [](Local<Value> value) {
                  ASSERT_TRUE(value->IsString());
                  EXPECT_EQ(2, String::Cast(*value)->Length());
                  EXPECT_EQ(kEmojiString, Utf8Value(value));
                });
}

TEST_F(ValueSerializerTest, DecodeString) {
  // Decoding the strings above from UTF-8.
  DecodeTest({0xff, 0x09, 0x53, 0x00},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsString());
               EXPECT_EQ(0, String::Cast(*value)->Length());
             });
  DecodeTest({0xff, 0x09, 0x53, 0x05, 'H', 'e', 'l', 'l', 'o'},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsString());
               EXPECT_EQ(5, String::Cast(*value)->Length());
               EXPECT_EQ(kHelloString, Utf8Value(value));
             });
  DecodeTest({0xff, 0x09, 0x53, 0x07, 'Q', 'u', 0xc3, 0xa9, 'b', 'e', 'c'},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsString());
               EXPECT_EQ(6, String::Cast(*value)->Length());
               EXPECT_EQ(kQuebecString, Utf8Value(value));
             });
  DecodeTest({0xff, 0x09, 0x53, 0x04, 0xf0, 0x9f, 0x91, 0x8a},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsString());
               EXPECT_EQ(2, String::Cast(*value)->Length());
               EXPECT_EQ(kEmojiString, Utf8Value(value));
             });

484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
  // And from Latin-1 (for the ones that fit).
  DecodeTest({0xff, 0x0a, 0x22, 0x00}, [](Local<Value> value) {
    ASSERT_TRUE(value->IsString());
    EXPECT_EQ(0, String::Cast(*value)->Length());
  });
  DecodeTest({0xff, 0x0a, 0x22, 0x05, 'H', 'e', 'l', 'l', 'o'},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsString());
               EXPECT_EQ(5, String::Cast(*value)->Length());
               EXPECT_EQ(kHelloString, Utf8Value(value));
             });
  DecodeTest({0xff, 0x0a, 0x22, 0x06, 'Q', 'u', 0xe9, 'b', 'e', 'c'},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsString());
               EXPECT_EQ(6, String::Cast(*value)->Length());
               EXPECT_EQ(kQuebecString, Utf8Value(value));
             });

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
// And from two-byte strings (endianness dependent).
#if defined(V8_TARGET_LITTLE_ENDIAN)
  DecodeTest({0xff, 0x09, 0x63, 0x00},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsString());
               EXPECT_EQ(0, String::Cast(*value)->Length());
             });
  DecodeTest({0xff, 0x09, 0x63, 0x0a, 'H', '\0', 'e', '\0', 'l', '\0', 'l',
              '\0', 'o', '\0'},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsString());
               EXPECT_EQ(5, String::Cast(*value)->Length());
               EXPECT_EQ(kHelloString, Utf8Value(value));
             });
  DecodeTest({0xff, 0x09, 0x63, 0x0c, 'Q', '\0', 'u', '\0', 0xe9, '\0', 'b',
              '\0', 'e', '\0', 'c', '\0'},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsString());
               EXPECT_EQ(6, String::Cast(*value)->Length());
               EXPECT_EQ(kQuebecString, Utf8Value(value));
             });
  DecodeTest({0xff, 0x09, 0x63, 0x04, 0x3d, 0xd8, 0x4a, 0xdc},
             [](Local<Value> value) {
               ASSERT_TRUE(value->IsString());
               EXPECT_EQ(2, String::Cast(*value)->Length());
               EXPECT_EQ(kEmojiString, Utf8Value(value));
             });
#endif
  // TODO(jbroman): The same for big-endian systems.
}

TEST_F(ValueSerializerTest, DecodeInvalidString) {
  // UTF-8 string with too few bytes available.
  InvalidDecodeTest({0xff, 0x09, 0x53, 0x10, 'v', '8'});
536 537
  // One-byte string with too few bytes available.
  InvalidDecodeTest({0xff, 0x0a, 0x22, 0x10, 'v', '8'});
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
#if defined(V8_TARGET_LITTLE_ENDIAN)
  // Two-byte string with too few bytes available.
  InvalidDecodeTest({0xff, 0x09, 0x63, 0x10, 'v', '\0', '8', '\0'});
  // Two-byte string with an odd byte length.
  InvalidDecodeTest({0xff, 0x09, 0x63, 0x03, 'v', '\0', '8'});
#endif
  // TODO(jbroman): The same for big-endian systems.
}

TEST_F(ValueSerializerTest, EncodeTwoByteStringUsesPadding) {
  // As long as the output has a version that Blink expects to be able to read,
  // we must respect its alignment requirements. It requires that two-byte
  // characters be aligned.
  EncodeTest(
      [this]() {
        // 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;
        return StringFromUtf8(string.c_str());
      },
      [](const std::vector<uint8_t>& data) {
562 563 564 565 566 567 568 569
        // 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);
570
        EXPECT_TRUE(std::equal(std::begin(expected_prefix),
571
                               std::end(expected_prefix), data.begin() + 2));
572 573 574
      });
}

575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
TEST_F(ValueSerializerTest, RoundTripDictionaryObject) {
  // Empty object.
  RoundTripTest("({})", [this](Local<Value> value) {
    ASSERT_TRUE(value->IsObject());
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getPrototypeOf(result) === Object.prototype"));
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getOwnPropertyNames(result).length === 0"));
  });
  // String key.
  RoundTripTest("({ a: 42 })", [this](Local<Value> value) {
    ASSERT_TRUE(value->IsObject());
    EXPECT_TRUE(EvaluateScriptForResultBool("result.hasOwnProperty('a')"));
    EXPECT_TRUE(EvaluateScriptForResultBool("result.a === 42"));
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getOwnPropertyNames(result).length === 1"));
  });
  // Integer key (treated as a string, but may be encoded differently).
  RoundTripTest("({ 42: 'a' })", [this](Local<Value> value) {
    ASSERT_TRUE(value->IsObject());
    EXPECT_TRUE(EvaluateScriptForResultBool("result.hasOwnProperty('42')"));
    EXPECT_TRUE(EvaluateScriptForResultBool("result[42] === 'a'"));
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getOwnPropertyNames(result).length === 1"));
  });
  // Key order must be preserved.
  RoundTripTest("({ x: 1, y: 2, a: 3 })", [this](Local<Value> value) {
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getOwnPropertyNames(result).toString() === 'x,y,a'"));
  });
  // A harder case of enumeration order.
  // Indexes first, in order (but not 2^32 - 1, which is not an index), then the
  // remaining (string) keys, in the order they were defined.
  RoundTripTest(
      "({ a: 2, 0xFFFFFFFF: 1, 0xFFFFFFFE: 3, 1: 0 })",
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getOwnPropertyNames(result).toString() === "
            "'1,4294967294,a,4294967295'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === 2"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result[0xFFFFFFFF] === 1"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result[0xFFFFFFFE] === 3"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result[1] === 0"));
      });
  // This detects a fairly subtle case: the object itself must be in the map
  // before its properties are deserialized, so that references to it can be
  // resolved.
  RoundTripTest(
      "(() => { var y = {}; y.self = y; return y; })()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsObject());
        EXPECT_TRUE(EvaluateScriptForResultBool("result === result.self"));
      });
}

TEST_F(ValueSerializerTest, DecodeDictionaryObject) {
  // Empty object.
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x6f, 0x7b, 0x00, 0x00},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsObject());
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === Object.prototype"));
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getOwnPropertyNames(result).length === 0"));
             });
  // String key.
  DecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x6f, 0x3f, 0x01, 0x53, 0x01, 0x61, 0x3f, 0x01,
       0x49, 0x54, 0x7b, 0x01},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsObject());
        EXPECT_TRUE(EvaluateScriptForResultBool("result.hasOwnProperty('a')"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === 42"));
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getOwnPropertyNames(result).length === 1"));
      });
  // Integer key (treated as a string, but may be encoded differently).
  DecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x6f, 0x3f, 0x01, 0x49, 0x54, 0x3f, 0x01, 0x53,
       0x01, 0x61, 0x7b, 0x01},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsObject());
        EXPECT_TRUE(EvaluateScriptForResultBool("result.hasOwnProperty('42')"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result[42] === 'a'"));
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getOwnPropertyNames(result).length === 1"));
      });
  // Key order must be preserved.
  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},
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getOwnPropertyNames(result).toString() === 'x,y,a'"));
      });
  // A harder case of enumeration order.
  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},
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getOwnPropertyNames(result).toString() === "
            "'1,4294967294,a,4294967295'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === 2"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result[0xFFFFFFFF] === 1"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result[0xFFFFFFFE] === 3"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result[1] === 0"));
      });
  // This detects a fairly subtle case: the object itself must be in the map
  // before its properties are deserialized, so that references to it can be
  // resolved.
  DecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x6f, 0x3f, 0x01, 0x53, 0x04, 0x73,
       0x65, 0x6c, 0x66, 0x3f, 0x01, 0x5e, 0x00, 0x7b, 0x01, 0x00},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsObject());
        EXPECT_TRUE(EvaluateScriptForResultBool("result === result.self"));
      });
}

699 700 701 702 703 704 705 706
TEST_F(ValueSerializerTest, InvalidDecodeObjectWithInvalidKeyType) {
  // Objects which would need conversion to string shouldn't be present as
  // object keys. The serializer would have obtained them from the own property
  // keys list, which should only contain names and indices.
  InvalidDecodeTest(
      {0xff, 0x09, 0x6f, 0x61, 0x00, 0x40, 0x00, 0x00, 0x7b, 0x01});
}

707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
TEST_F(ValueSerializerTest, RoundTripOnlyOwnEnumerableStringKeys) {
  // Only "own" properties should be serialized, not ones on the prototype.
  RoundTripTest("(() => { var x = {}; x.__proto__ = {a: 4}; return x; })()",
                [this](Local<Value> value) {
                  EXPECT_TRUE(EvaluateScriptForResultBool("!('a' in result)"));
                });
  // Only enumerable properties should be serialized.
  RoundTripTest(
      "(() => {"
      "  var x = {};"
      "  Object.defineProperty(x, 'a', {value: 1, enumerable: false});"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("!('a' in result)"));
      });
  // Symbol keys should not be serialized.
  RoundTripTest("({ [Symbol()]: 4 })", [this](Local<Value> value) {
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getOwnPropertySymbols(result).length === 0"));
  });
}

TEST_F(ValueSerializerTest, RoundTripTrickyGetters) {
  // Keys are enumerated before any setters are called, but if there is no own
  // property when the value is to be read, then it should not be serialized.
  RoundTripTest("({ get a() { delete this.b; return 1; }, b: 2 })",
                [this](Local<Value> value) {
                  EXPECT_TRUE(EvaluateScriptForResultBool("!('b' in result)"));
                });
  // Keys added after the property enumeration should not be serialized.
  RoundTripTest("({ get a() { this.b = 3; }})", [this](Local<Value> value) {
    EXPECT_TRUE(EvaluateScriptForResultBool("!('b' in result)"));
  });
  // But if you remove a key and add it back, that's fine. But it will appear in
  // the original place in enumeration order.
  RoundTripTest(
      "({ get a() { delete this.b; this.b = 4; }, b: 2, c: 3 })",
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getOwnPropertyNames(result).toString() === 'a,b,c'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.b === 4"));
      });
  // Similarly, it only matters if a property was enumerable when the
  // enumeration happened.
  RoundTripTest(
      "({ get a() {"
      "    Object.defineProperty(this, 'b', {value: 2, enumerable: false});"
      "}, b: 1})",
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("result.b === 2"));
      });
  RoundTripTest(
      "(() => {"
      "  var x = {"
      "    get a() {"
      "      Object.defineProperty(this, 'b', {value: 2, enumerable: true});"
      "    }"
      "  };"
      "  Object.defineProperty(x, 'b',"
      "      {value: 1, enumerable: false, configurable: true});"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("!('b' in result)"));
      });
  // The property also should not be read if it can only be found on the
  // prototype chain (but not as an own property) after enumeration.
  RoundTripTest(
      "(() => {"
      "  var x = { get a() { delete this.b; }, b: 1 };"
      "  x.__proto__ = { b: 0 };"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("!('b' in result)"));
      });
  // If an exception is thrown by script, encoding must fail and the exception
  // must be thrown.
  InvalidEncodeTest("({ get a() { throw new Error('sentinel'); } })",
                    [](Local<Message> message) {
                      ASSERT_FALSE(message.IsEmpty());
                      EXPECT_NE(std::string::npos,
                                Utf8Value(message->Get()).find("sentinel"));
                    });
}

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
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}]");
}

819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
TEST_F(ValueSerializerTest, DecodeDictionaryObjectVersion0) {
  // Empty object.
  DecodeTestForVersion0(
      {0x7b, 0x00},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsObject());
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getPrototypeOf(result) === Object.prototype"));
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getOwnPropertyNames(result).length === 0"));
      });
  // String key.
  DecodeTestForVersion0(
      {0x53, 0x01, 0x61, 0x49, 0x54, 0x7b, 0x01, 0x00},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsObject());
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getPrototypeOf(result) === Object.prototype"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.hasOwnProperty('a')"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === 42"));
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getOwnPropertyNames(result).length === 1"));
      });
  // Integer key (treated as a string, but may be encoded differently).
  DecodeTestForVersion0(
      {0x49, 0x54, 0x53, 0x01, 0x61, 0x7b, 0x01, 0x00},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsObject());
        EXPECT_TRUE(EvaluateScriptForResultBool("result.hasOwnProperty('42')"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result[42] === 'a'"));
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getOwnPropertyNames(result).length === 1"));
      });
  // Key order must be preserved.
  DecodeTestForVersion0(
      {0x53, 0x01, 0x78, 0x49, 0x02, 0x53, 0x01, 0x79, 0x49, 0x04, 0x53, 0x01,
       0x61, 0x49, 0x06, 0x7b, 0x03, 0x00},
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getOwnPropertyNames(result).toString() === 'x,y,a'"));
      });
  // A property and an element.
  DecodeTestForVersion0(
      {0x49, 0x54, 0x53, 0x01, 0x61, 0x53, 0x01, 0x61, 0x49, 0x54, 0x7b, 0x02},
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getOwnPropertyNames(result).toString() === '42,a'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result[42] === 'a'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === 42"));
      });
}

871 872 873 874
TEST_F(ValueSerializerTest, RoundTripArray) {
  // A simple array of integers.
  RoundTripTest("[1, 2, 3, 4, 5]", [this](Local<Value> value) {
    ASSERT_TRUE(value->IsArray());
875
    EXPECT_EQ(5u, Array::Cast(*value)->Length());
876 877 878 879 880 881 882 883 884 885
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getPrototypeOf(result) === Array.prototype"));
    EXPECT_TRUE(
        EvaluateScriptForResultBool("result.toString() === '1,2,3,4,5'"));
  });
  // A long (sparse) array.
  RoundTripTest(
      "(() => { var x = new Array(1000); x[500] = 42; return x; })()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
886
        EXPECT_EQ(1000u, Array::Cast(*value)->Length());
887 888 889 890 891 892
        EXPECT_TRUE(EvaluateScriptForResultBool("result[500] === 42"));
      });
  // Duplicate reference.
  RoundTripTest(
      "(() => { var y = {}; return [y, y]; })()", [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
893
        ASSERT_EQ(2u, Array::Cast(*value)->Length());
894 895 896 897 898 899 900
        EXPECT_TRUE(EvaluateScriptForResultBool("result[0] === result[1]"));
      });
  // Duplicate reference in a sparse array.
  RoundTripTest(
      "(() => { var x = new Array(1000); x[1] = x[500] = {}; return x; })()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
901
        ASSERT_EQ(1000u, Array::Cast(*value)->Length());
902 903 904 905 906 907 908 909 910
        EXPECT_TRUE(
            EvaluateScriptForResultBool("typeof result[1] === 'object'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result[1] === result[500]"));
      });
  // Self reference.
  RoundTripTest(
      "(() => { var y = []; y[0] = y; return y; })()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
911
        ASSERT_EQ(1u, Array::Cast(*value)->Length());
912 913 914 915 916 917 918
        EXPECT_TRUE(EvaluateScriptForResultBool("result[0] === result"));
      });
  // Self reference in a sparse array.
  RoundTripTest(
      "(() => { var y = new Array(1000); y[519] = y; return y; })()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
919
        ASSERT_EQ(1000u, Array::Cast(*value)->Length());
920 921 922 923 924 925 926
        EXPECT_TRUE(EvaluateScriptForResultBool("result[519] === result"));
      });
  // Array with additional properties.
  RoundTripTest(
      "(() => { var y = [1, 2]; y.foo = 'bar'; return y; })()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
927
        ASSERT_EQ(2u, Array::Cast(*value)->Length());
928 929 930 931 932 933 934 935
        EXPECT_TRUE(EvaluateScriptForResultBool("result.toString() === '1,2'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.foo === 'bar'"));
      });
  // Sparse array with additional properties.
  RoundTripTest(
      "(() => { var y = new Array(1000); y.foo = 'bar'; return y; })()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
936
        ASSERT_EQ(1000u, Array::Cast(*value)->Length());
937 938 939 940 941 942 943
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "result.toString() === ','.repeat(999)"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.foo === 'bar'"));
      });
  // The distinction between holes and undefined elements must be maintained.
  RoundTripTest("[,undefined]", [this](Local<Value> value) {
    ASSERT_TRUE(value->IsArray());
944
    ASSERT_EQ(2u, Array::Cast(*value)->Length());
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960
    EXPECT_TRUE(
        EvaluateScriptForResultBool("typeof result[0] === 'undefined'"));
    EXPECT_TRUE(
        EvaluateScriptForResultBool("typeof result[1] === 'undefined'"));
    EXPECT_TRUE(EvaluateScriptForResultBool("!result.hasOwnProperty(0)"));
    EXPECT_TRUE(EvaluateScriptForResultBool("result.hasOwnProperty(1)"));
  });
}

TEST_F(ValueSerializerTest, DecodeArray) {
  // A simple array of integers.
  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},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsArray());
961
               EXPECT_EQ(5u, Array::Cast(*value)->Length());
962 963 964 965 966 967 968 969 970 971
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === Array.prototype"));
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "result.toString() === '1,2,3,4,5'"));
             });
  // A long (sparse) array.
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x61, 0xe8, 0x07, 0x3f, 0x01, 0x49,
              0xe8, 0x07, 0x3f, 0x01, 0x49, 0x54, 0x40, 0x01, 0xe8, 0x07},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsArray());
972
               EXPECT_EQ(1000u, Array::Cast(*value)->Length());
973 974 975 976 977 978 979 980
               EXPECT_TRUE(EvaluateScriptForResultBool("result[500] === 42"));
             });
  // Duplicate reference.
  DecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x41, 0x02, 0x3f, 0x01, 0x6f, 0x7b, 0x00, 0x3f,
       0x02, 0x5e, 0x01, 0x24, 0x00, 0x02},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
981
        ASSERT_EQ(2u, Array::Cast(*value)->Length());
982 983 984 985 986 987 988 989 990
        EXPECT_TRUE(EvaluateScriptForResultBool("result[0] === result[1]"));
      });
  // Duplicate reference in a sparse array.
  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},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
991
        ASSERT_EQ(1000u, Array::Cast(*value)->Length());
992 993 994 995 996 997 998 999 1000
        EXPECT_TRUE(
            EvaluateScriptForResultBool("typeof result[1] === 'object'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result[1] === result[500]"));
      });
  // Self reference.
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x41, 0x01, 0x3f, 0x01, 0x5e, 0x00, 0x24,
              0x00, 0x01, 0x00},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsArray());
1001
               ASSERT_EQ(1u, Array::Cast(*value)->Length());
1002 1003 1004 1005 1006 1007 1008 1009
               EXPECT_TRUE(EvaluateScriptForResultBool("result[0] === result"));
             });
  // Self reference in a sparse array.
  DecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x61, 0xe8, 0x07, 0x3f, 0x01, 0x49,
       0x8e, 0x08, 0x3f, 0x01, 0x5e, 0x00, 0x40, 0x01, 0xe8, 0x07},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1010
        ASSERT_EQ(1000u, Array::Cast(*value)->Length());
1011 1012 1013 1014 1015 1016 1017 1018 1019
        EXPECT_TRUE(EvaluateScriptForResultBool("result[519] === result"));
      });
  // Array with additional properties.
  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},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1020
        ASSERT_EQ(2u, Array::Cast(*value)->Length());
1021 1022 1023 1024 1025 1026 1027 1028 1029
        EXPECT_TRUE(EvaluateScriptForResultBool("result.toString() === '1,2'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.foo === 'bar'"));
      });
  // Sparse array with additional properties.
  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},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsArray());
1030
               ASSERT_EQ(1000u, Array::Cast(*value)->Length());
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "result.toString() === ','.repeat(999)"));
               EXPECT_TRUE(EvaluateScriptForResultBool("result.foo === 'bar'"));
             });
  // 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.
  DecodeTest(
      {0xff, 0x09, 0x61, 0x02, 0x49, 0x02, 0x5f, 0x40, 0x01, 0x02},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1042
        ASSERT_EQ(2u, Array::Cast(*value)->Length());
1043 1044 1045 1046 1047 1048 1049 1050 1051
        EXPECT_TRUE(
            EvaluateScriptForResultBool("typeof result[0] === 'undefined'"));
        EXPECT_TRUE(
            EvaluateScriptForResultBool("typeof result[1] === 'undefined'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("!result.hasOwnProperty(0)"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.hasOwnProperty(1)"));
      });
}

1052 1053 1054 1055 1056 1057 1058 1059
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).
  InvalidDecodeTest({0xff, 0x09, 0x41, 0x80, 0x80, 0x80, 0x80, 0x04});
  // Not so large, but there isn't enough data left in the buffer.
  InvalidDecodeTest({0xff, 0x09, 0x41, 0x01});
}

1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
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.
  RoundTripTest(
      "(() => {"
      "  var x = [1,2,3];"
      "  Object.defineProperty(x, '1', {enumerable:false, value:5});"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1072
        ASSERT_EQ(3u, Array::Cast(*value)->Length());
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
        EXPECT_TRUE(EvaluateScriptForResultBool("!result.hasOwnProperty('1')"));
      });
}

TEST_F(ValueSerializerTest, RoundTripArrayWithTrickyGetters) {
  // If an element is deleted before it is serialized, then it's deleted.
  RoundTripTest(
      "(() => {"
      "  var x = [{ get a() { delete x[1]; }}, 42];"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1086
        ASSERT_EQ(2u, Array::Cast(*value)->Length());
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
        EXPECT_TRUE(
            EvaluateScriptForResultBool("typeof result[1] === 'undefined'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("!result.hasOwnProperty(1)"));
      });
  // Same for sparse arrays.
  RoundTripTest(
      "(() => {"
      "  var x = [{ get a() { delete x[1]; }}, 42];"
      "  x.length = 1000;"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1100
        ASSERT_EQ(1000u, Array::Cast(*value)->Length());
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
        EXPECT_TRUE(
            EvaluateScriptForResultBool("typeof result[1] === 'undefined'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("!result.hasOwnProperty(1)"));
      });
  // If the length is changed, then the resulting array still has the original
  // length, but elements that were not yet serialized are gone.
  RoundTripTest(
      "(() => {"
      "  var x = [1, { get a() { x.length = 0; }}, 3, 4];"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1114
        ASSERT_EQ(4u, Array::Cast(*value)->Length());
1115 1116 1117
        EXPECT_TRUE(EvaluateScriptForResultBool("result[0] === 1"));
        EXPECT_TRUE(EvaluateScriptForResultBool("!result.hasOwnProperty(2)"));
      });
1118 1119 1120 1121 1122 1123 1124 1125 1126
  // The same is true if the length is shortened, but there are still items
  // remaining.
  RoundTripTest(
      "(() => {"
      "  var x = [1, { get a() { x.length = 3; }}, 3, 4];"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1127
        ASSERT_EQ(4u, Array::Cast(*value)->Length());
1128 1129 1130
        EXPECT_TRUE(EvaluateScriptForResultBool("result[2] === 3"));
        EXPECT_TRUE(EvaluateScriptForResultBool("!result.hasOwnProperty(3)"));
      });
1131 1132 1133 1134 1135 1136 1137 1138 1139
  // Same for sparse arrays.
  RoundTripTest(
      "(() => {"
      "  var x = [1, { get a() { x.length = 0; }}, 3, 4];"
      "  x.length = 1000;"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1140
        ASSERT_EQ(1000u, Array::Cast(*value)->Length());
1141 1142 1143
        EXPECT_TRUE(EvaluateScriptForResultBool("result[0] === 1"));
        EXPECT_TRUE(EvaluateScriptForResultBool("!result.hasOwnProperty(2)"));
      });
1144 1145 1146 1147 1148 1149 1150 1151
  RoundTripTest(
      "(() => {"
      "  var x = [1, { get a() { x.length = 3; }}, 3, 4];"
      "  x.length = 1000;"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1152
        ASSERT_EQ(1000u, Array::Cast(*value)->Length());
1153 1154 1155
        EXPECT_TRUE(EvaluateScriptForResultBool("result[2] === 3"));
        EXPECT_TRUE(EvaluateScriptForResultBool("!result.hasOwnProperty(3)"));
      });
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
  // If a getter makes a property non-enumerable, it should still be enumerated
  // as enumeration happens once before getters are invoked.
  RoundTripTest(
      "(() => {"
      "  var x = [{ get a() {"
      "    Object.defineProperty(x, '1', { value: 3, enumerable: false });"
      "  }}, 2];"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1167
        ASSERT_EQ(2u, Array::Cast(*value)->Length());
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
        EXPECT_TRUE(EvaluateScriptForResultBool("result[1] === 3"));
      });
  // Same for sparse arrays.
  RoundTripTest(
      "(() => {"
      "  var x = [{ get a() {"
      "    Object.defineProperty(x, '1', { value: 3, enumerable: false });"
      "  }}, 2];"
      "  x.length = 1000;"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1181
        ASSERT_EQ(1000u, Array::Cast(*value)->Length());
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
        EXPECT_TRUE(EvaluateScriptForResultBool("result[1] === 3"));
      });
  // Getters on the array itself must also run.
  RoundTripTest(
      "(() => {"
      "  var x = [1, 2, 3];"
      "  Object.defineProperty(x, '1', { enumerable: true, get: () => 4 });"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1193
        ASSERT_EQ(3u, Array::Cast(*value)->Length());
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
        EXPECT_TRUE(EvaluateScriptForResultBool("result[1] === 4"));
      });
  // Same for sparse arrays.
  RoundTripTest(
      "(() => {"
      "  var x = [1, 2, 3];"
      "  Object.defineProperty(x, '1', { enumerable: true, get: () => 4 });"
      "  x.length = 1000;"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1206
        ASSERT_EQ(1000u, Array::Cast(*value)->Length());
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
        EXPECT_TRUE(EvaluateScriptForResultBool("result[1] === 4"));
      });
  // Even with a getter that deletes things, we don't read from the prototype.
  RoundTripTest(
      "(() => {"
      "  var x = [{ get a() { delete x[1]; } }, 2];"
      "  x.__proto__ = Object.create(Array.prototype, { 1: { value: 6 } });"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1218
        ASSERT_EQ(2u, Array::Cast(*value)->Length());
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230
        EXPECT_TRUE(EvaluateScriptForResultBool("!(1 in result)"));
      });
  // Same for sparse arrays.
  RoundTripTest(
      "(() => {"
      "  var x = [{ get a() { delete x[1]; } }, 2];"
      "  x.__proto__ = Object.create(Array.prototype, { 1: { value: 6 } });"
      "  x.length = 1000;"
      "  return x;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1231
        ASSERT_EQ(1000u, Array::Cast(*value)->Length());
1232 1233 1234 1235
        EXPECT_TRUE(EvaluateScriptForResultBool("!(1 in result)"));
      });
}

1236 1237 1238
TEST_F(ValueSerializerTest, DecodeSparseArrayVersion0) {
  // Empty (sparse) array.
  DecodeTestForVersion0({0x40, 0x00, 0x00, 0x00},
krasin's avatar
krasin committed
1239
                        [](Local<Value> value) {
1240
                          ASSERT_TRUE(value->IsArray());
1241
                          ASSERT_EQ(0u, Array::Cast(*value)->Length());
1242 1243 1244 1245 1246 1247 1248 1249
                        });
  // Sparse array with a mixture of elements and properties.
  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},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1250
        EXPECT_EQ(3u, Array::Cast(*value)->Length());
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
        EXPECT_TRUE(
            EvaluateScriptForResultBool("result.toString() === 'a,,5'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("!(1 in result)"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.foo === 'bar'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.baz === -6"));
      });
  // Sparse array in a sparse array (sanity check of nesting).
  DecodeTestForVersion0(
      {0x55, 0x01, 0x55, 0x01, 0x54, 0x40, 0x01, 0x02, 0x40, 0x01, 0x02, 0x00},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsArray());
1262
        EXPECT_EQ(2u, Array::Cast(*value)->Length());
1263 1264 1265 1266 1267 1268 1269
        EXPECT_TRUE(EvaluateScriptForResultBool("!(0 in result)"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result[1] instanceof Array"));
        EXPECT_TRUE(EvaluateScriptForResultBool("!(0 in result[1])"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result[1][1] === true"));
      });
}

1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
TEST_F(ValueSerializerTest, RoundTripDenseArrayContainingUndefined) {
  // In previous serialization versions, this would be interpreted as an absent
  // property.
  RoundTripTest("[undefined]", [this](Local<Value> value) {
    ASSERT_TRUE(value->IsArray());
    EXPECT_EQ(1u, Array::Cast(*value)->Length());
    EXPECT_TRUE(EvaluateScriptForResultBool("result.hasOwnProperty(0)"));
    EXPECT_TRUE(EvaluateScriptForResultBool("result[0] === undefined"));
  });
}

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.
  DecodeTest({0xff, 0x09, 0x41, 0x01, 0x5f, 0x24, 0x00, 0x01},
             [this](Local<Value> value) {
               EXPECT_TRUE(EvaluateScriptForResultBool("!(0 in result)"));
             });
  DecodeTest(
      {0xff, 0x0b, 0x41, 0x01, 0x5f, 0x24, 0x00, 0x01},
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("0 in result"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result[0] === undefined"));
      });
  DecodeTest({0xff, 0x0b, 0x41, 0x01, 0x2d, 0x24, 0x00, 0x01},
             [this](Local<Value> value) {
               EXPECT_TRUE(EvaluateScriptForResultBool("!(0 in result)"));
             });
}

1300
TEST_F(ValueSerializerTest, RoundTripDate) {
krasin's avatar
krasin committed
1301
  RoundTripTest("new Date(1e6)", [](Local<Value> value) {
1302 1303 1304 1305
    ASSERT_TRUE(value->IsDate());
    EXPECT_EQ(1e6, Date::Cast(*value)->ValueOf());
    EXPECT_TRUE("Object.getPrototypeOf(result) === Date.prototype");
  });
krasin's avatar
krasin committed
1306
  RoundTripTest("new Date(Date.UTC(1867, 6, 1))", [](Local<Value> value) {
1307 1308 1309
    ASSERT_TRUE(value->IsDate());
    EXPECT_TRUE("result.toISOString() === '1867-07-01T00:00:00.000Z'");
  });
krasin's avatar
krasin committed
1310
  RoundTripTest("new Date(NaN)", [](Local<Value> value) {
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
    ASSERT_TRUE(value->IsDate());
    EXPECT_TRUE(std::isnan(Date::Cast(*value)->ValueOf()));
  });
  RoundTripTest(
      "({ a: new Date(), get b() { return this.a; } })",
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a instanceof Date"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
      });
}

TEST_F(ValueSerializerTest, DecodeDate) {
1323
#if defined(V8_TARGET_LITTLE_ENDIAN)
1324 1325
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x80, 0x84,
              0x2e, 0x41, 0x00},
krasin's avatar
krasin committed
1326
             [](Local<Value> value) {
1327 1328 1329 1330 1331 1332 1333
               ASSERT_TRUE(value->IsDate());
               EXPECT_EQ(1e6, Date::Cast(*value)->ValueOf());
               EXPECT_TRUE("Object.getPrototypeOf(result) === Date.prototype");
             });
  DecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x44, 0x00, 0x00, 0x20, 0x45, 0x27, 0x89, 0x87,
       0xc2, 0x00},
krasin's avatar
krasin committed
1334
      [](Local<Value> value) {
1335 1336 1337 1338 1339
        ASSERT_TRUE(value->IsDate());
        EXPECT_TRUE("result.toISOString() === '1867-07-01T00:00:00.000Z'");
      });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
              0xf8, 0x7f, 0x00},
krasin's avatar
krasin committed
1340
             [](Local<Value> value) {
1341 1342 1343
               ASSERT_TRUE(value->IsDate());
               EXPECT_TRUE(std::isnan(Date::Cast(*value)->ValueOf()));
             });
1344 1345 1346
#else
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x44, 0x41, 0x2e, 0x84, 0x80, 0x00, 0x00,
              0x00, 0x00, 0x00},
1347
             [](Local<Value> value) {
1348 1349 1350 1351 1352 1353 1354
               ASSERT_TRUE(value->IsDate());
               EXPECT_EQ(1e6, Date::Cast(*value)->ValueOf());
               EXPECT_TRUE("Object.getPrototypeOf(result) === Date.prototype");
             });
  DecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x44, 0xc2, 0x87, 0x89, 0x27, 0x45, 0x20, 0x00,
       0x00, 0x00},
1355
      [](Local<Value> value) {
1356 1357 1358 1359 1360
        ASSERT_TRUE(value->IsDate());
        EXPECT_TRUE("result.toISOString() === '1867-07-01T00:00:00.000Z'");
      });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x44, 0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00,
              0x00, 0x00, 0x00},
1361
             [](Local<Value> value) {
1362 1363 1364 1365
               ASSERT_TRUE(value->IsDate());
               EXPECT_TRUE(std::isnan(Date::Cast(*value)->ValueOf()));
             });
#endif
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
  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},
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a instanceof Date"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
      });
}

1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
TEST_F(ValueSerializerTest, RoundTripValueObjects) {
  RoundTripTest("new Boolean(true)", [this](Local<Value> value) {
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getPrototypeOf(result) === Boolean.prototype"));
    EXPECT_TRUE(EvaluateScriptForResultBool("result.valueOf() === true"));
  });
  RoundTripTest("new Boolean(false)", [this](Local<Value> value) {
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getPrototypeOf(result) === Boolean.prototype"));
    EXPECT_TRUE(EvaluateScriptForResultBool("result.valueOf() === false"));
  });
  RoundTripTest(
      "({ a: new Boolean(true), get b() { return this.a; }})",
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a instanceof Boolean"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
      });
  RoundTripTest("new Number(-42)", [this](Local<Value> value) {
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getPrototypeOf(result) === Number.prototype"));
    EXPECT_TRUE(EvaluateScriptForResultBool("result.valueOf() === -42"));
  });
  RoundTripTest("new Number(NaN)", [this](Local<Value> value) {
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getPrototypeOf(result) === Number.prototype"));
    EXPECT_TRUE(EvaluateScriptForResultBool("Number.isNaN(result.valueOf())"));
  });
  RoundTripTest(
      "({ a: new Number(6), get b() { return this.a; }})",
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a instanceof Number"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
      });
  RoundTripTest("new String('Qu\\xe9bec')", [this](Local<Value> value) {
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getPrototypeOf(result) === String.prototype"));
    EXPECT_TRUE(
        EvaluateScriptForResultBool("result.valueOf() === 'Qu\\xe9bec'"));
    EXPECT_TRUE(EvaluateScriptForResultBool("result.length === 6"));
  });
  RoundTripTest("new String('\\ud83d\\udc4a')", [this](Local<Value> value) {
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getPrototypeOf(result) === String.prototype"));
    EXPECT_TRUE(
        EvaluateScriptForResultBool("result.valueOf() === '\\ud83d\\udc4a'"));
    EXPECT_TRUE(EvaluateScriptForResultBool("result.length === 2"));
  });
  RoundTripTest(
      "({ a: new String(), get b() { return this.a; }})",
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a instanceof String"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
      });
}

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

TEST_F(ValueSerializerTest, DecodeValueObjects) {
  DecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x79, 0x00},
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getPrototypeOf(result) === Boolean.prototype"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.valueOf() === true"));
      });
  DecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x78, 0x00},
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getPrototypeOf(result) === Boolean.prototype"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.valueOf() === false"));
      });
  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},
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a instanceof Boolean"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
      });
1458
#if defined(V8_TARGET_LITTLE_ENDIAN)
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
  DecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45,
       0xc0, 0x00},
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getPrototypeOf(result) === Number.prototype"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.valueOf() === -42"));
      });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
              0xf8, 0x7f, 0x00},
             [this](Local<Value> value) {
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === Number.prototype"));
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Number.isNaN(result.valueOf())"));
             });
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
#else
  DecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x6e, 0xc0, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00},
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getPrototypeOf(result) === Number.prototype"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.valueOf() === -42"));
      });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x6e, 0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00,
              0x00, 0x00, 0x00},
             [this](Local<Value> value) {
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === Number.prototype"));
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Number.isNaN(result.valueOf())"));
             });
#endif
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
  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},
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a instanceof Number"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
      });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x73, 0x07, 0x51, 0x75, 0xc3, 0xa9, 0x62,
              0x65, 0x63, 0x00},
             [this](Local<Value> value) {
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === String.prototype"));
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "result.valueOf() === 'Qu\\xe9bec'"));
               EXPECT_TRUE(EvaluateScriptForResultBool("result.length === 6"));
             });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x73, 0x04, 0xf0, 0x9f, 0x91, 0x8a},
             [this](Local<Value> value) {
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === String.prototype"));
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "result.valueOf() === '\\ud83d\\udc4a'"));
               EXPECT_TRUE(EvaluateScriptForResultBool("result.length === 2"));
             });
  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},
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a instanceof String"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
      });
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535

  // String object containing a Latin-1 string.
  DecodeTest({0xff, 0x0c, 0x73, 0x22, 0x06, 'Q', 'u', 0xe9, 'b', 'e', 'c'},
             [this](Local<Value> value) {
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === String.prototype"));
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "result.valueOf() === 'Qu\\xe9bec'"));
               EXPECT_TRUE(EvaluateScriptForResultBool("result.length === 6"));
             });
1536 1537
}

1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
TEST_F(ValueSerializerTest, RoundTripRegExp) {
  RoundTripTest("/foo/g", [this](Local<Value> value) {
    ASSERT_TRUE(value->IsRegExp());
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getPrototypeOf(result) === RegExp.prototype"));
    EXPECT_TRUE(EvaluateScriptForResultBool("result.toString() === '/foo/g'"));
  });
  RoundTripTest("new RegExp('Qu\\xe9bec', 'i')", [this](Local<Value> value) {
    ASSERT_TRUE(value->IsRegExp());
    EXPECT_TRUE(
        EvaluateScriptForResultBool("result.toString() === '/Qu\\xe9bec/i'"));
  });
  RoundTripTest("new RegExp('\\ud83d\\udc4a', 'ug')",
                [this](Local<Value> value) {
                  ASSERT_TRUE(value->IsRegExp());
                  EXPECT_TRUE(EvaluateScriptForResultBool(
                      "result.toString() === '/\\ud83d\\udc4a/gu'"));
                });
  RoundTripTest(
      "({ a: /foo/gi, get b() { return this.a; }})",
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a instanceof RegExp"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
      });
}

TEST_F(ValueSerializerTest, DecodeRegExp) {
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x52, 0x03, 0x66, 0x6f, 0x6f, 0x01},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsRegExp());
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === RegExp.prototype"));
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "result.toString() === '/foo/g'"));
             });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x52, 0x07, 0x51, 0x75, 0xc3, 0xa9, 0x62,
              0x65, 0x63, 0x02},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsRegExp());
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "result.toString() === '/Qu\\xe9bec/i'"));
             });
  DecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x52, 0x04, 0xf0, 0x9f, 0x91, 0x8a, 0x11, 0x00},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsRegExp());
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "result.toString() === '/\\ud83d\\udc4a/gu'"));
      });
  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},
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a instanceof RegExp"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
      });
1595 1596 1597 1598 1599 1600 1601 1602 1603

  // RegExp containing a Latin-1 string.
  DecodeTest(
      {0xff, 0x0c, 0x52, 0x22, 0x06, 'Q', 'u', 0xe9, 'b', 'e', 'c', 0x02},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsRegExp());
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "result.toString() === '/Qu\\xe9bec/i'"));
      });
1604 1605
}

1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
// Tests that invalid flags are not accepted by the deserializer. In particular,
// the dotAll flag ('s') is only valid when the corresponding flag is enabled.
TEST_F(ValueSerializerTest, DecodeRegExpDotAll) {
  i::FLAG_harmony_regexp_dotall = false;
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x52, 0x03, 0x66, 0x6f, 0x6f, 0x1f},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsRegExp());
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === RegExp.prototype"));
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "result.toString() === '/foo/gimuy'"));
             });
  InvalidDecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x52, 0x03, 0x66, 0x6f, 0x6f, 0x3f});
  InvalidDecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x52, 0x03, 0x66, 0x6f, 0x6f, 0x7f});

  i::FLAG_harmony_regexp_dotall = true;
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x52, 0x03, 0x66, 0x6f, 0x6f, 0x1f},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsRegExp());
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === RegExp.prototype"));
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "result.toString() === '/foo/gimuy'"));
             });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x52, 0x03, 0x66, 0x6f, 0x6f, 0x3f},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsRegExp());
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === RegExp.prototype"));
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "result.toString() === '/foo/gimsuy'"));
             });
  InvalidDecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x52, 0x03, 0x66, 0x6f, 0x6f, 0x7f});
}

1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
TEST_F(ValueSerializerTest, RoundTripMap) {
  RoundTripTest(
      "(() => { var m = new Map(); m.set(42, 'foo'); return m; })()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsMap());
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getPrototypeOf(result) === Map.prototype"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.size === 1"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.get(42) === 'foo'"));
      });
  RoundTripTest("(() => { var m = new Map(); m.set(m, m); return m; })()",
                [this](Local<Value> value) {
                  ASSERT_TRUE(value->IsMap());
                  EXPECT_TRUE(EvaluateScriptForResultBool("result.size === 1"));
                  EXPECT_TRUE(EvaluateScriptForResultBool(
                      "result.get(result) === result"));
                });
  // Iteration order must be preserved.
  RoundTripTest(
      "(() => {"
      "  var m = new Map();"
      "  m.set(1, 0); m.set('a', 0); m.set(3, 0); m.set(2, 0);"
      "  return m;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsMap());
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Array.from(result.keys()).toString() === '1,a,3,2'"));
      });
}

TEST_F(ValueSerializerTest, DecodeMap) {
  DecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x3b, 0x3f, 0x01, 0x49, 0x54, 0x3f, 0x01, 0x53,
       0x03, 0x66, 0x6f, 0x6f, 0x3a, 0x02},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsMap());
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getPrototypeOf(result) === Map.prototype"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.size === 1"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.get(42) === 'foo'"));
      });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x3b, 0x3f, 0x01, 0x5e, 0x00, 0x3f, 0x01,
              0x5e, 0x00, 0x3a, 0x02, 0x00},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsMap());
               EXPECT_TRUE(EvaluateScriptForResultBool("result.size === 1"));
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "result.get(result) === result"));
             });
  // Iteration order must be preserved.
  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},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsMap());
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Array.from(result.keys()).toString() === '1,a,3,2'"));
             });
}

TEST_F(ValueSerializerTest, RoundTripMapWithTrickyGetters) {
  // Even if an entry is removed or reassigned, the original key/value pair is
  // used.
  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');"
      "  return m;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsMap());
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Array.from(result.keys()).toString() === '0,1,2'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.get(1) === 'foo'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.get(2) === 'bar'"));
      });
  // However, deeper modifications of objects yet to be serialized still apply.
  RoundTripTest(
      "(() => {"
      "  var m = new Map();"
      "  var key = { get a() { value.foo = 'bar'; } };"
      "  var value = { get a() { key.baz = 'quux'; } };"
      "  m.set(key, value);"
      "  return m;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsMap());
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "!('baz' in Array.from(result.keys())[0])"));
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Array.from(result.values())[0].foo === 'bar'"));
      });
}

TEST_F(ValueSerializerTest, RoundTripSet) {
  RoundTripTest(
      "(() => { var s = new Set(); s.add(42); s.add('foo'); return s; })()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsSet());
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getPrototypeOf(result) === Set.prototype"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.size === 2"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.has(42)"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.has('foo')"));
      });
  RoundTripTest(
      "(() => { var s = new Set(); s.add(s); return s; })()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsSet());
        EXPECT_TRUE(EvaluateScriptForResultBool("result.size === 1"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.has(result)"));
      });
  // Iteration order must be preserved.
  RoundTripTest(
      "(() => {"
      "  var s = new Set();"
      "  s.add(1); s.add('a'); s.add(3); s.add(2);"
      "  return s;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsSet());
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Array.from(result.keys()).toString() === '1,a,3,2'"));
      });
}

TEST_F(ValueSerializerTest, DecodeSet) {
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x27, 0x3f, 0x01, 0x49, 0x54, 0x3f, 0x01,
              0x53, 0x03, 0x66, 0x6f, 0x6f, 0x2c, 0x02},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsSet());
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === Set.prototype"));
               EXPECT_TRUE(EvaluateScriptForResultBool("result.size === 2"));
               EXPECT_TRUE(EvaluateScriptForResultBool("result.has(42)"));
               EXPECT_TRUE(EvaluateScriptForResultBool("result.has('foo')"));
             });
  DecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x27, 0x3f, 0x01, 0x5e, 0x00, 0x2c, 0x01, 0x00},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsSet());
        EXPECT_TRUE(EvaluateScriptForResultBool("result.size === 1"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.has(result)"));
      });
  // Iteration order must be preserved.
  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},
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsSet());
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Array.from(result.keys()).toString() === '1,a,3,2'"));
      });
}

TEST_F(ValueSerializerTest, RoundTripSetWithTrickyGetters) {
  // Even if an element is added or removed during serialization, the original
  // set of elements is used.
  RoundTripTest(
      "(() => {"
      "  var s = new Set();"
      "  s.add({ get a() { s.delete(1); s.add(2); } });"
      "  s.add(1);"
      "  return s;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsSet());
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Array.from(result.keys()).toString() === '[object Object],1'"));
      });
  // However, deeper modifications of objects yet to be serialized still apply.
  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);"
      "  return s;"
      "})()",
      [this](Local<Value> value) {
        ASSERT_TRUE(value->IsSet());
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "!('baz' in Array.from(result.keys())[0])"));
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Array.from(result.keys())[1].foo === 'bar'"));
      });
}

1839 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 1887 1888 1889 1890 1891
TEST_F(ValueSerializerTest, RoundTripArrayBuffer) {
  RoundTripTest("new ArrayBuffer()", [this](Local<Value> value) {
    ASSERT_TRUE(value->IsArrayBuffer());
    EXPECT_EQ(0u, ArrayBuffer::Cast(*value)->ByteLength());
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getPrototypeOf(result) === ArrayBuffer.prototype"));
  });
  RoundTripTest("new Uint8Array([0, 128, 255]).buffer",
                [this](Local<Value> value) {
                  ASSERT_TRUE(value->IsArrayBuffer());
                  EXPECT_EQ(3u, ArrayBuffer::Cast(*value)->ByteLength());
                  EXPECT_TRUE(EvaluateScriptForResultBool(
                      "new Uint8Array(result).toString() === '0,128,255'"));
                });
  RoundTripTest(
      "({ a: new ArrayBuffer(), get b() { return this.a; }})",
      [this](Local<Value> value) {
        EXPECT_TRUE(
            EvaluateScriptForResultBool("result.a instanceof ArrayBuffer"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
      });
}

TEST_F(ValueSerializerTest, DecodeArrayBuffer) {
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x42, 0x00},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsArrayBuffer());
               EXPECT_EQ(0u, ArrayBuffer::Cast(*value)->ByteLength());
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === ArrayBuffer.prototype"));
             });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x42, 0x03, 0x00, 0x80, 0xff, 0x00},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsArrayBuffer());
               EXPECT_EQ(3u, ArrayBuffer::Cast(*value)->ByteLength());
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "new Uint8Array(result).toString() === '0,128,255'"));
             });
  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},
      [this](Local<Value> value) {
        EXPECT_TRUE(
            EvaluateScriptForResultBool("result.a instanceof ArrayBuffer"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
      });
}

TEST_F(ValueSerializerTest, DecodeInvalidArrayBuffer) {
  InvalidDecodeTest({0xff, 0x09, 0x42, 0xff, 0xff, 0x00});
}

1892 1893 1894 1895 1896
// 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; }
1897 1898
  void* Reserve(size_t length) override { return nullptr; }
  void Free(void* data, size_t length, AllocationMode mode) override {}
1899
  void Free(void*, size_t) override {}
1900 1901
  void SetProtection(void* data, size_t length,
                     Protection protection) override {}
1902 1903 1904 1905 1906 1907 1908 1909 1910
};

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);
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
  {
    Isolate::Scope isolate_scope(isolate);
    HandleScope handle_scope(isolate);
    Local<Context> context = Context::New(isolate);
    Context::Scope context_scope(context);
    TryCatch try_catch(isolate);

    const std::vector<uint8_t> data = {0xff, 0x09, 0x3f, 0x00, 0x42,
                                       0x03, 0x00, 0x80, 0xff, 0x00};
    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();
1929 1930
}

1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
// 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);
      const uint8_t data[kTestByteLength] = {0x00, 0x01, 0x80, 0xff};
      memcpy(output_buffer_->GetContents().Data(), data, kTestByteLength);
    }
  }

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

1957 1958
  void AfterEncode() override { input_buffer_->Neuter(); }

1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
  void BeforeDecode(ValueDeserializer* deserializer) override {
    deserializer->TransferArrayBuffer(0, output_buffer_);
  }

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

TEST_F(ValueSerializerTestWithArrayBufferTransfer,
       RoundTripArrayBufferTransfer) {
  RoundTripTest([this]() { return input_buffer(); },
                [this](Local<Value> value) {
                  ASSERT_TRUE(value->IsArrayBuffer());
                  EXPECT_EQ(output_buffer(), value);
                  EXPECT_TRUE(EvaluateScriptForResultBool(
                      "new Uint8Array(result).toString() === '0,1,128,255'"));
                });
  RoundTripTest(
      [this]() {
        Local<Object> 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));
        return object;
      },
      [this](Local<Value> value) {
        EXPECT_TRUE(
            EvaluateScriptForResultBool("result.a instanceof ArrayBuffer"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "new Uint8Array(result.a).toString() === '0,1,128,255'"));
      });
}

2001 2002 2003 2004 2005 2006
TEST_F(ValueSerializerTest, RoundTripTypedArray) {
// Check that the right type comes out the other side for every kind of typed
// array.
#define TYPED_ARRAY_ROUND_TRIP_TEST(Type, type, TYPE, ctype, size)      \
  RoundTripTest("new " #Type "Array(2)", [this](Local<Value> value) {   \
    ASSERT_TRUE(value->Is##Type##Array());                              \
2007 2008
    EXPECT_EQ(2u * size, TypedArray::Cast(*value)->ByteLength());       \
    EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());                  \
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
    EXPECT_TRUE(EvaluateScriptForResultBool(                            \
        "Object.getPrototypeOf(result) === " #Type "Array.prototype")); \
  });
  TYPED_ARRAYS(TYPED_ARRAY_ROUND_TRIP_TEST)
#undef TYPED_ARRAY_CASE

  // Check that values of various kinds are suitably preserved.
  RoundTripTest("new Uint8Array([1, 128, 255])", [this](Local<Value> value) {
    EXPECT_TRUE(
        EvaluateScriptForResultBool("result.toString() === '1,128,255'"));
  });
  RoundTripTest("new Int16Array([0, 256, -32768])", [this](Local<Value> value) {
    EXPECT_TRUE(
        EvaluateScriptForResultBool("result.toString() === '0,256,-32768'"));
  });
  RoundTripTest("new Float32Array([0, -0.5, NaN, Infinity])",
                [this](Local<Value> value) {
                  EXPECT_TRUE(EvaluateScriptForResultBool(
                      "result.toString() === '0,-0.5,NaN,Infinity'"));
                });

  // Array buffer views sharing a buffer should do so on the other side.
  // Similarly, multiple references to the same typed array should be resolved.
  RoundTripTest(
      "(() => {"
      "  var buffer = new ArrayBuffer(32);"
      "  return {"
      "    u8: new Uint8Array(buffer),"
      "    get u8_2() { return this.u8; },"
      "    f32: new Float32Array(buffer, 4, 5),"
      "    b: buffer,"
      "  };"
      "})()",
      [this](Local<Value> value) {
        EXPECT_TRUE(
            EvaluateScriptForResultBool("result.u8 instanceof Uint8Array"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.u8 === result.u8_2"));
        EXPECT_TRUE(
            EvaluateScriptForResultBool("result.f32 instanceof Float32Array"));
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "result.u8.buffer === result.f32.buffer"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.f32.byteOffset === 4"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.f32.length === 5"));
      });
}

TEST_F(ValueSerializerTest, DecodeTypedArray) {
  // Check that the right type comes out the other side for every kind of typed
  // array.
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x3f, 0x00, 0x42, 0x02, 0x00, 0x00, 0x56,
              0x42, 0x00, 0x02},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsUint8Array());
2062 2063
               EXPECT_EQ(2u, TypedArray::Cast(*value)->ByteLength());
               EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
2064 2065 2066 2067 2068 2069 2070
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === Uint8Array.prototype"));
             });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x3f, 0x00, 0x42, 0x02, 0x00, 0x00, 0x56,
              0x62, 0x00, 0x02},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsInt8Array());
2071 2072
               EXPECT_EQ(2u, TypedArray::Cast(*value)->ByteLength());
               EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
2073 2074 2075 2076 2077 2078 2079 2080
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === Int8Array.prototype"));
             });
#if defined(V8_TARGET_LITTLE_ENDIAN)
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x3f, 0x00, 0x42, 0x04, 0x00, 0x00, 0x00,
              0x00, 0x56, 0x57, 0x00, 0x04},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsUint16Array());
2081 2082
               EXPECT_EQ(4u, TypedArray::Cast(*value)->ByteLength());
               EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
2083 2084 2085 2086 2087 2088 2089
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === Uint16Array.prototype"));
             });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x3f, 0x00, 0x42, 0x04, 0x00, 0x00, 0x00,
              0x00, 0x56, 0x77, 0x00, 0x04},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsInt16Array());
2090 2091
               EXPECT_EQ(4u, TypedArray::Cast(*value)->ByteLength());
               EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
2092 2093 2094 2095 2096 2097 2098
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === Int16Array.prototype"));
             });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x3f, 0x00, 0x42, 0x08, 0x00, 0x00,
              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x44, 0x00, 0x08},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsUint32Array());
2099 2100
               EXPECT_EQ(8u, TypedArray::Cast(*value)->ByteLength());
               EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
2101 2102 2103 2104 2105 2106 2107
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === Uint32Array.prototype"));
             });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x3f, 0x00, 0x42, 0x08, 0x00, 0x00,
              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x64, 0x00, 0x08},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsInt32Array());
2108 2109
               EXPECT_EQ(8u, TypedArray::Cast(*value)->ByteLength());
               EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
2110 2111 2112 2113 2114 2115 2116
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === Int32Array.prototype"));
             });
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x3f, 0x00, 0x42, 0x08, 0x00, 0x00,
              0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x56, 0x66, 0x00, 0x08},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsFloat32Array());
2117 2118
               EXPECT_EQ(8u, TypedArray::Cast(*value)->ByteLength());
               EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
2119 2120 2121 2122 2123 2124 2125 2126
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === Float32Array.prototype"));
             });
  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},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsFloat64Array());
2127 2128
               EXPECT_EQ(16u, TypedArray::Cast(*value)->ByteLength());
               EXPECT_EQ(2u, TypedArray::Cast(*value)->Length());
2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 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
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === Float64Array.prototype"));
             });
#endif  // V8_TARGET_LITTLE_ENDIAN

  // Check that values of various kinds are suitably preserved.
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x3f, 0x00, 0x42, 0x03, 0x01, 0x80, 0xff,
              0x56, 0x42, 0x00, 0x03, 0x00},
             [this](Local<Value> value) {
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "result.toString() === '1,128,255'"));
             });
#if defined(V8_TARGET_LITTLE_ENDIAN)
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x3f, 0x00, 0x42, 0x06, 0x00, 0x00, 0x00,
              0x01, 0x00, 0x80, 0x56, 0x77, 0x00, 0x06},
             [this](Local<Value> value) {
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "result.toString() === '0,256,-32768'"));
             });
  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},
             [this](Local<Value> value) {
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "result.toString() === '0,-0.5,NaN,Infinity'"));
             });
#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.
  DecodeTest(
      {0xff, 0x09, 0x3f, 0x00, 0x6f, 0x3f, 0x01, 0x53, 0x02, 0x75, 0x38, 0x3f,
       0x01, 0x3f, 0x01, 0x42, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
       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,
       0x53, 0x01, 0x62, 0x3f, 0x04, 0x5e, 0x01, 0x7b, 0x04, 0x00},
      [this](Local<Value> value) {
        EXPECT_TRUE(
            EvaluateScriptForResultBool("result.u8 instanceof Uint8Array"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.u8 === result.u8_2"));
        EXPECT_TRUE(
            EvaluateScriptForResultBool("result.f32 instanceof Float32Array"));
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "result.u8.buffer === result.f32.buffer"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.f32.byteOffset === 4"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.f32.length === 5"));
      });
}

TEST_F(ValueSerializerTest, DecodeInvalidTypedArray) {
  // Byte offset out of range.
  InvalidDecodeTest(
      {0xff, 0x09, 0x42, 0x02, 0x00, 0x00, 0x56, 0x42, 0x03, 0x01});
  // Byte offset in range, offset + length out of range.
  InvalidDecodeTest(
      {0xff, 0x09, 0x42, 0x02, 0x00, 0x00, 0x56, 0x42, 0x01, 0x03});
  // Byte offset not divisible by element size.
  InvalidDecodeTest(
      {0xff, 0x09, 0x42, 0x04, 0x00, 0x00, 0x00, 0x00, 0x56, 0x77, 0x01, 0x02});
  // Byte length not divisible by element size.
  InvalidDecodeTest(
      {0xff, 0x09, 0x42, 0x04, 0x00, 0x00, 0x00, 0x00, 0x56, 0x77, 0x02, 0x01});
2194 2195 2196
  // Invalid view type (0xff).
  InvalidDecodeTest(
      {0xff, 0x09, 0x42, 0x02, 0x00, 0x00, 0x56, 0xff, 0x01, 0x01});
2197 2198 2199 2200 2201 2202
}

TEST_F(ValueSerializerTest, RoundTripDataView) {
  RoundTripTest("new DataView(new ArrayBuffer(4), 1, 2)",
                [this](Local<Value> value) {
                  ASSERT_TRUE(value->IsDataView());
2203 2204 2205
                  EXPECT_EQ(1u, DataView::Cast(*value)->ByteOffset());
                  EXPECT_EQ(2u, DataView::Cast(*value)->ByteLength());
                  EXPECT_EQ(4u, DataView::Cast(*value)->Buffer()->ByteLength());
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
                  EXPECT_TRUE(EvaluateScriptForResultBool(
                      "Object.getPrototypeOf(result) === DataView.prototype"));
                });
}

TEST_F(ValueSerializerTest, DecodeDataView) {
  DecodeTest({0xff, 0x09, 0x3f, 0x00, 0x3f, 0x00, 0x42, 0x04, 0x00, 0x00, 0x00,
              0x00, 0x56, 0x3f, 0x01, 0x02},
             [this](Local<Value> value) {
               ASSERT_TRUE(value->IsDataView());
2216 2217 2218
               EXPECT_EQ(1u, DataView::Cast(*value)->ByteOffset());
               EXPECT_EQ(2u, DataView::Cast(*value)->ByteLength());
               EXPECT_EQ(4u, DataView::Cast(*value)->Buffer()->ByteLength());
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
               EXPECT_TRUE(EvaluateScriptForResultBool(
                   "Object.getPrototypeOf(result) === DataView.prototype"));
             });
}

TEST_F(ValueSerializerTest, DecodeInvalidDataView) {
  // Byte offset out of range.
  InvalidDecodeTest(
      {0xff, 0x09, 0x42, 0x02, 0x00, 0x00, 0x56, 0x3f, 0x03, 0x01});
  // Byte offset in range, offset + length out of range.
  InvalidDecodeTest(
      {0xff, 0x09, 0x42, 0x02, 0x00, 0x00, 0x56, 0x3f, 0x01, 0x03});
}

2233 2234 2235 2236 2237
class ValueSerializerTestWithSharedArrayBufferTransfer
    : public ValueSerializerTest {
 protected:
  static const size_t kTestByteLength = 4;

2238 2239
  ValueSerializerTestWithSharedArrayBufferTransfer()
      : serializer_delegate_(this) {
2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
    const uint8_t data[kTestByteLength] = {0x00, 0x01, 0x80, 0xff};
    memcpy(data_, data, kTestByteLength);
    {
      Context::Scope scope(serialization_context());
      input_buffer_ =
          SharedArrayBuffer::New(isolate(), &data_, kTestByteLength);
    }
    {
      Context::Scope scope(deserialization_context());
      output_buffer_ =
          SharedArrayBuffer::New(isolate(), &data_, kTestByteLength);
    }
  }

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

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

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

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 2299 2300 2301 2302 2303 2304 2305
 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(
        ValueSerializerTestWithSharedArrayBufferTransfer* test)
        : test_(test) {}
    MOCK_METHOD2(GetSharedArrayBufferId,
                 Maybe<uint32_t>(Isolate* isolate,
                                 Local<SharedArrayBuffer> shared_array_buffer));
    void ThrowDataCloneError(Local<String> message) override {
      test_->isolate()->ThrowException(Exception::Error(message));
    }

   private:
    ValueSerializerTestWithSharedArrayBufferTransfer* test_;
  };

#if __clang__
#pragma clang diagnostic pop
#endif

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

  SerializerDelegate serializer_delegate_;

2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317
 private:
  static bool flag_was_enabled_;
  uint8_t data_[kTestByteLength];
  Local<SharedArrayBuffer> input_buffer_;
  Local<SharedArrayBuffer> output_buffer_;
};

bool ValueSerializerTestWithSharedArrayBufferTransfer::flag_was_enabled_ =
    false;

TEST_F(ValueSerializerTestWithSharedArrayBufferTransfer,
       RoundTripSharedArrayBufferTransfer) {
2318 2319 2320 2321
  EXPECT_CALL(serializer_delegate_,
              GetSharedArrayBufferId(isolate(), input_buffer()))
      .WillRepeatedly(Return(Just(0U)));

2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352
  RoundTripTest([this]() { return input_buffer(); },
                [this](Local<Value> value) {
                  ASSERT_TRUE(value->IsSharedArrayBuffer());
                  EXPECT_EQ(output_buffer(), value);
                  EXPECT_TRUE(EvaluateScriptForResultBool(
                      "new Uint8Array(result).toString() === '0,1,128,255'"));
                });
  RoundTripTest(
      [this]() {
        Local<Object> 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));
        return object;
      },
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "result.a instanceof SharedArrayBuffer"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "new Uint8Array(result.a).toString() === '0,1,128,255'"));
      });
}

2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424
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;
};

2425 2426 2427
// This is a tag that is used in V8. Using this ensures that we have separate
// tag namespaces.
const uint8_t ValueSerializerTestWithHostObject::kExampleHostObjectTag = 'T';
2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 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 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505

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);
      }));
  RoundTripTest("new ExampleHostObject(42)", [this](Local<Value> value) {
    ASSERT_TRUE(value->IsObject());
    ASSERT_TRUE(Object::Cast(*value)->InternalFieldCount());
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getPrototypeOf(result) === ExampleHostObject.prototype"));
    EXPECT_TRUE(EvaluateScriptForResultBool("result.value === 42"));
  });
  RoundTripTest(
      "new ExampleHostObject(0xCAFECAFE)", [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("result.value === 0xCAFECAFE"));
      });
}

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);
      }));
  RoundTripTest("new ExampleHostObject(42, 0)", [this](Local<Value> value) {
    ASSERT_TRUE(value->IsObject());
    ASSERT_TRUE(Object::Cast(*value)->InternalFieldCount());
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getPrototypeOf(result) === ExampleHostObject.prototype"));
    EXPECT_TRUE(EvaluateScriptForResultBool("result.value === 42"));
    EXPECT_TRUE(EvaluateScriptForResultBool("result.value2 === 0"));
  });
  RoundTripTest(
      "new ExampleHostObject(0xFFFFFFFF, 0x12345678)",
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool("result.value === 0xFFFFFFFF"));
        EXPECT_TRUE(
            EvaluateScriptForResultBool("result.value2 === 0x12345678"));
      });
}

2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543
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);
      }));
  RoundTripTest("new ExampleHostObject(-3.5)", [this](Local<Value> value) {
    ASSERT_TRUE(value->IsObject());
    ASSERT_TRUE(Object::Cast(*value)->InternalFieldCount());
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getPrototypeOf(result) === ExampleHostObject.prototype"));
    EXPECT_TRUE(EvaluateScriptForResultBool("result.value === -3.5"));
  });
  RoundTripTest("new ExampleHostObject(NaN)", [this](Local<Value> value) {
    EXPECT_TRUE(EvaluateScriptForResultBool("Number.isNaN(result.value)"));
  });
  RoundTripTest("new ExampleHostObject(Infinity)", [this](Local<Value> value) {
    EXPECT_TRUE(EvaluateScriptForResultBool("result.value === Infinity"));
  });
  RoundTripTest("new ExampleHostObject(-0)", [this](Local<Value> value) {
    EXPECT_TRUE(EvaluateScriptForResultBool("1/result.value === -Infinity"));
  });
}

2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599
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);
      }));
  RoundTripTest("new ExampleHostObject()", [this](Local<Value> value) {
    ASSERT_TRUE(value->IsObject());
    ASSERT_TRUE(Object::Cast(*value)->InternalFieldCount());
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "Object.getPrototypeOf(result) === ExampleHostObject.prototype"));
  });
}

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);
      }));
  RoundTripTest(
      "({ a: new ExampleHostObject(), get b() { return this.a; }})",
      [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "result.a instanceof ExampleHostObject"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
      });
}

2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612
TEST_F(ValueSerializerTestWithHostObject, DecodeSimpleHostObject) {
  EXPECT_CALL(deserializer_delegate_, ReadHostObject(isolate()))
      .WillRepeatedly(Invoke([this](Isolate*) {
        EXPECT_TRUE(ReadExampleHostObjectTag());
        return NewHostObject(deserialization_context(), 0, nullptr);
      }));
  DecodeTest(
      {0xff, 0x0d, 0x5c, kExampleHostObjectTag}, [this](Local<Value> value) {
        EXPECT_TRUE(EvaluateScriptForResultBool(
            "Object.getPrototypeOf(result) === ExampleHostObject.prototype"));
      });
}

2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644
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(
      "({ a: new Uint8Array([1, 2, 3]), get b() { return this.a; }})",
      [this](Local<Value> value) {
        EXPECT_TRUE(
            EvaluateScriptForResultBool("result.a instanceof Uint8Array"));
        EXPECT_TRUE(
            EvaluateScriptForResultBool("result.a.toString() === '4,5,6'"));
        EXPECT_TRUE(EvaluateScriptForResultBool("result.a === result.b"));
      });
}

2645 2646 2647 2648
// 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.

2649 2650 2651 2652 2653 2654 2655 2656
// 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,
};

2657
class ValueSerializerTestWithWasm : public ValueSerializerTest {
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 2686
 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_;
  }

2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699
 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;
  }

2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825
  class ThrowingSerializer : public ValueSerializer::Delegate {
   public:
    Maybe<uint32_t> GetWasmModuleTransferId(
        Isolate* isolate, Local<WasmCompiledModule> module) override {
      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:
    SerializeToTransfer(
        std::vector<WasmCompiledModule::TransferrableModule>* modules)
        : modules_(modules) {}
    Maybe<uint32_t> GetWasmModuleTransferId(
        Isolate* isolate, Local<WasmCompiledModule> module) override {
      modules_->push_back(module->GetTransferrableModule());
      return Just(static_cast<uint32_t>(modules_->size()) - 1);
    }

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

   private:
    std::vector<WasmCompiledModule::TransferrableModule>* modules_;
  };

  class DeserializeFromTransfer : public ValueDeserializer::Delegate {
   public:
    DeserializeFromTransfer(
        std::vector<WasmCompiledModule::TransferrableModule>* modules)
        : modules_(modules) {}

    MaybeLocal<WasmCompiledModule> GetWasmModuleFromId(Isolate* isolate,
                                                       uint32_t id) override {
      return WasmCompiledModule::FromTransferrableModule(isolate,
                                                         modules_->at(id));
    }

   private:
    std::vector<WasmCompiledModule::TransferrableModule>* modules_;
  };

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

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

  Local<WasmCompiledModule> MakeWasm() {
    return WasmCompiledModule::DeserializeOrCompile(
               isolate(), {nullptr, 0},
               {kIncrementerWasm, sizeof(kIncrementerWasm)})
        .ToLocalChecked();
  }

  void ExpectPass() {
    RoundTripTest(
        [this]() { return MakeWasm(); },
        [this](Local<Value> value) {
          ASSERT_TRUE(value->IsWebAssemblyCompiledModule());
          EXPECT_TRUE(EvaluateScriptForResultBool(
              "new WebAssembly.Instance(result).exports.increment(8) === 9"));
        });
  }

  void ExpectFail() {
    EncodeTest(
        [this]() { return MakeWasm(); },
        [this](const std::vector<uint8_t>& data) { InvalidDecodeTest(data); });
  }

  Local<Value> GetComplexObjectWithDuplicate() {
    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());
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "result.mod1 instanceof WebAssembly.Module"));
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "result.mod2 instanceof WebAssembly.Module"));
    EXPECT_TRUE(EvaluateScriptForResultBool("result.num === 2"));
  }

  Local<Value> GetComplexObjectWithMany() {
    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();
  }

2826 2827
 private:
  static bool g_saved_flag;
2828 2829 2830 2831 2832 2833 2834
  std::vector<WasmCompiledModule::TransferrableModule> transfer_modules_;
  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_;
2835 2836 2837
};

bool ValueSerializerTestWithWasm::g_saved_flag = false;
2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858
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();
  InvalidEncodeTest(
      [this]() { return MakeWasm(); },
      [](Local<Message> message) {
        size_t msg_len = static_cast<size_t>(message->Get()->Length());
        std::unique_ptr<char[]> buff(new char[msg_len + 1]);
        message->Get()->WriteOneByte(reinterpret_cast<uint8_t*>(buff.get()));
        // 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);
      });
}
2859

2860 2861 2862 2863 2864 2865 2866 2867
// The default deserializer throws if wasm transfer is attempted
TEST_F(ValueSerializerTestWithWasm, DefaultDeserializationDelegate) {
  EnableTransferSerialization();
  EnableDefaultDeserializer();
  EncodeTest(
      [this]() { return MakeWasm(); },
      [this](const std::vector<uint8_t>& data) { InvalidDecodeTest(data); });
}
mtrofin's avatar
mtrofin committed
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
// 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();
mtrofin's avatar
mtrofin committed
2901
  RoundTripTest(
2902
      [this]() { return GetComplexObjectWithDuplicate(); },
mtrofin's avatar
mtrofin committed
2903
      [this](Local<Value> value) {
2904 2905 2906 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
        VerifyComplexObject(value);
        EXPECT_TRUE(EvaluateScriptForResultBool("result.mod1 === result.mod2"));
      });
}

TEST_F(ValueSerializerTestWithWasm, ComplexObjectDuplicateInline) {
  SetExpectInlineWasm(true);
  RoundTripTest(
      [this]() { return GetComplexObjectWithDuplicate(); },
      [this](Local<Value> value) {
        VerifyComplexObject(value);
        EXPECT_TRUE(EvaluateScriptForResultBool("result.mod1 === result.mod2"));
      });
}

TEST_F(ValueSerializerTestWithWasm, ComplexObjectWithManyTransfer) {
  EnableTransferSerialization();
  EnableTransferDeserialization();
  RoundTripTest(
      [this]() { return GetComplexObjectWithMany(); },
      [this](Local<Value> value) {
        VerifyComplexObject(value);
        EXPECT_TRUE(EvaluateScriptForResultBool("result.mod1 != result.mod2"));
      });
}

TEST_F(ValueSerializerTestWithWasm, ComplexObjectWithManyInline) {
  SetExpectInlineWasm(true);
  RoundTripTest(
      [this]() { return GetComplexObjectWithMany(); },
      [this](Local<Value> value) {
        VerifyComplexObject(value);
        EXPECT_TRUE(EvaluateScriptForResultBool("result.mod1 != result.mod2"));
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 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001
      });
}

// As produced around Chrome 56.
const unsigned char kSerializedIncrementerWasm[] = {
    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,
    0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x07, 0x08, 0x00, 0x00, 0x09, 0x04,
    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,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x23, 0x88, 0x42, 0x32, 0x03,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x00,
    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,
    0x66, 0x90, 0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x44, 0x00,
    0x00, 0x00, 0xff, 0xff, 0xff, 0x0f, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    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,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x23, 0x88, 0x42, 0x32, 0x03, 0x00,
    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};

TEST_F(ValueSerializerTestWithWasm, DecodeWasmModule) {
3002
  if (true) return;  // TODO(mtrofin): fix this test
3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022
  std::vector<uint8_t> raw(
      kSerializedIncrementerWasm,
      kSerializedIncrementerWasm + sizeof(kSerializedIncrementerWasm));
  DecodeTest(raw, [this](Local<Value> value) {
    ASSERT_TRUE(value->IsWebAssemblyCompiledModule());
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "new WebAssembly.Instance(result).exports.increment(8) === 9"));
  });
}

// As above, but with empty compiled data. Should work due to fallback to wire
// data.
const unsigned char kSerializedIncrementerWasmWithInvalidCompiledData[] = {
    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};

TEST_F(ValueSerializerTestWithWasm, DecodeWasmModuleWithInvalidCompiledData) {
3023
  if (true) return;  // TODO(titzer): regenerate this test
3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051
  std::vector<uint8_t> raw(
      kSerializedIncrementerWasmWithInvalidCompiledData,
      kSerializedIncrementerWasmWithInvalidCompiledData +
          sizeof(kSerializedIncrementerWasmWithInvalidCompiledData));
  DecodeTest(raw, [this](Local<Value> value) {
    ASSERT_TRUE(value->IsWebAssemblyCompiledModule());
    EXPECT_TRUE(EvaluateScriptForResultBool(
        "new WebAssembly.Instance(result).exports.increment(8) === 9"));
  });
}

// As above, but also with empty wire data. Should fail.
const unsigned char kSerializedIncrementerWasmInvalid[] = {
    0xff, 0x09, 0x3f, 0x00, 0x57, 0x79, 0x00, 0x00};

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

TEST_F(ValueSerializerTestWithWasm, DecodeWasmModuleWithInvalidDataLength) {
  InvalidDecodeTest({0xff, 0x09, 0x3f, 0x00, 0x57, 0x79, 0x7f, 0x00});
  InvalidDecodeTest({0xff, 0x09, 0x3f, 0x00, 0x57, 0x79, 0x00, 0x7f});
}

3052 3053
}  // namespace
}  // namespace v8