test-serialize.cc 43.3 KB
Newer Older
1
// Copyright 2007-2010 the V8 project authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//     * Neither the name of Google Inc. nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <signal.h>

30
#include <sys/stat.h>
31

32
#include "src/v8.h"
33

34
#include "src/bootstrapper.h"
35
#include "src/compilation-cache.h"
36
#include "src/debug.h"
37
#include "src/heap/spaces.h"
38 39
#include "src/natives.h"
#include "src/objects.h"
40
#include "src/runtime/runtime.h"
41 42 43 44
#include "src/scopeinfo.h"
#include "src/serialize.h"
#include "src/snapshot.h"
#include "test/cctest/cctest.h"
45 46 47 48 49 50

using namespace v8::internal;


template <class T>
static Address AddressOf(T id) {
51
  return ExternalReference(id, CcTest::i_isolate()).address();
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
}


template <class T>
static uint32_t Encode(const ExternalReferenceEncoder& encoder, T id) {
  return encoder.Encode(AddressOf(id));
}


static int make_code(TypeCode type, int id) {
  return static_cast<uint32_t>(type) << kReferenceTypeShift | id;
}


TEST(ExternalReferenceEncoder) {
67
  Isolate* isolate = CcTest::i_isolate();
68 69
  v8::V8::Initialize();

70
  ExternalReferenceEncoder encoder(isolate);
71 72
  CHECK_EQ(make_code(BUILTIN, Builtins::kArrayCode),
           Encode(encoder, Builtins::kArrayCode));
73
  CHECK_EQ(make_code(v8::internal::RUNTIME_FUNCTION, Runtime::kAbort),
74
           Encode(encoder, Runtime::kAbort));
75
  ExternalReference stack_limit_address =
76
      ExternalReference::address_of_stack_limit(isolate);
77
  CHECK_EQ(make_code(UNCLASSIFIED, 2),
78 79
           encoder.Encode(stack_limit_address.address()));
  ExternalReference real_stack_limit_address =
80
      ExternalReference::address_of_real_stack_limit(isolate);
81
  CHECK_EQ(make_code(UNCLASSIFIED, 3),
82
           encoder.Encode(real_stack_limit_address.address()));
83
  CHECK_EQ(make_code(UNCLASSIFIED, 8),
84
           encoder.Encode(ExternalReference::debug_break(isolate).address()));
85 86 87 88 89 90 91
  CHECK_EQ(
      make_code(UNCLASSIFIED, 4),
      encoder.Encode(ExternalReference::new_space_start(isolate).address()));
  CHECK_EQ(
      make_code(UNCLASSIFIED, 1),
      encoder.Encode(ExternalReference::roots_array_start(isolate).address()));
  CHECK_EQ(make_code(UNCLASSIFIED, 34),
92
           encoder.Encode(ExternalReference::cpu_features().address()));
93 94 95 96
}


TEST(ExternalReferenceDecoder) {
97
  Isolate* isolate = CcTest::i_isolate();
98 99
  v8::V8::Initialize();

100
  ExternalReferenceDecoder decoder(isolate);
101 102
  CHECK_EQ(AddressOf(Builtins::kArrayCode),
           decoder.Decode(make_code(BUILTIN, Builtins::kArrayCode)));
103
  CHECK_EQ(AddressOf(Runtime::kAbort),
104 105
           decoder.Decode(make_code(v8::internal::RUNTIME_FUNCTION,
                                    Runtime::kAbort)));
106
  CHECK_EQ(ExternalReference::address_of_stack_limit(isolate).address(),
107
           decoder.Decode(make_code(UNCLASSIFIED, 2)));
108
  CHECK_EQ(ExternalReference::address_of_real_stack_limit(isolate).address(),
109
           decoder.Decode(make_code(UNCLASSIFIED, 3)));
110
  CHECK_EQ(ExternalReference::debug_break(isolate).address(),
111
           decoder.Decode(make_code(UNCLASSIFIED, 8)));
112
  CHECK_EQ(ExternalReference::new_space_start(isolate).address(),
113
           decoder.Decode(make_code(UNCLASSIFIED, 4)));
114 115 116
}


117 118 119
class FileByteSink : public SnapshotByteSink {
 public:
  explicit FileByteSink(const char* snapshot_file) {
120
    fp_ = v8::base::OS::FOpen(snapshot_file, "wb");
121 122 123 124 125 126 127 128 129 130 131
    file_name_ = snapshot_file;
    if (fp_ == NULL) {
      PrintF("Unable to write to snapshot file \"%s\"\n", snapshot_file);
      exit(1);
    }
  }
  virtual ~FileByteSink() {
    if (fp_ != NULL) {
      fclose(fp_);
    }
  }
132
  virtual void Put(byte b, const char* description) {
133
    if (fp_ != NULL) {
134
      fputc(b, fp_);
135 136 137 138 139
    }
  }
  virtual int Position() {
    return ftell(fp_);
  }
140
  void WriteSpaceUsed(Serializer* serializer);
141 142 143 144 145 146 147

 private:
  FILE* fp_;
  const char* file_name_;
};


148
void FileByteSink::WriteSpaceUsed(Serializer* ser) {
149
  int file_name_length = StrLength(file_name_) + 10;
150
  Vector<char> name = Vector<char>::New(file_name_length + 1);
151
  SNPrintF(name, "%s.size", file_name_);
152
  FILE* fp = v8::base::OS::FOpen(name.start(), "w");
153
  name.Dispose();
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178

  Vector<const uint32_t> chunks = ser->FinalAllocationChunks(NEW_SPACE);
  CHECK_EQ(1, chunks.length());
  fprintf(fp, "new %d\n", chunks[0]);
  chunks = ser->FinalAllocationChunks(OLD_POINTER_SPACE);
  CHECK_EQ(1, chunks.length());
  fprintf(fp, "pointer %d\n", chunks[0]);
  chunks = ser->FinalAllocationChunks(OLD_DATA_SPACE);
  CHECK_EQ(1, chunks.length());
  fprintf(fp, "data %d\n", chunks[0]);
  chunks = ser->FinalAllocationChunks(CODE_SPACE);
  CHECK_EQ(1, chunks.length());
  fprintf(fp, "code %d\n", chunks[0]);
  chunks = ser->FinalAllocationChunks(MAP_SPACE);
  CHECK_EQ(1, chunks.length());
  fprintf(fp, "map %d\n", chunks[0]);
  chunks = ser->FinalAllocationChunks(CELL_SPACE);
  CHECK_EQ(1, chunks.length());
  fprintf(fp, "cell %d\n", chunks[0]);
  chunks = ser->FinalAllocationChunks(PROPERTY_CELL_SPACE);
  CHECK_EQ(1, chunks.length());
  fprintf(fp, "property cell %d\n", chunks[0]);
  chunks = ser->FinalAllocationChunks(LO_SPACE);
  CHECK_EQ(1, chunks.length());
  fprintf(fp, "lo %d\n", chunks[0]);
179 180 181 182
  fclose(fp);
}


183
static bool WriteToFile(Isolate* isolate, const char* snapshot_file) {
184
  FileByteSink file(snapshot_file);
185
  StartupSerializer ser(isolate, &file);
186
  ser.Serialize();
187
  ser.FinalizeAllocation();
188

189
  file.WriteSpaceUsed(&ser);
190

191 192 193 194
  return true;
}


195
static void Serialize(v8::Isolate* isolate) {
196 197 198 199
  // We have to create one context.  One reason for this is so that the builtins
  // can be loaded from v8natives.js and their addresses can be processed.  This
  // will clear the pending fixups array, which would otherwise contain GC roots
  // that would confuse the serialization/deserialization process.
200
  v8::Isolate::Scope isolate_scope(isolate);
201 202 203 204
  {
    v8::HandleScope scope(isolate);
    v8::Context::New(isolate);
  }
205

206
  Isolate* internal_isolate = reinterpret_cast<Isolate*>(isolate);
207
  internal_isolate->heap()->CollectAllAvailableGarbage("serialize");
208
  WriteToFile(internal_isolate, FLAG_testing_serialization_file);
209 210 211
}


212
// Test that the whole heap can be serialized.
213
UNINITIALIZED_TEST(Serialize) {
214
  if (!Snapshot::HaveASnapshotToStartFrom()) {
215 216 217 218
    v8::Isolate::CreateParams params;
    params.enable_serializer = true;
    v8::Isolate* isolate = v8::Isolate::New(params);
    Serialize(isolate);
219
  }
220 221 222
}


223
// Test that heap serialization is non-destructive.
224
UNINITIALIZED_TEST(SerializeTwice) {
225
  if (!Snapshot::HaveASnapshotToStartFrom()) {
226 227 228 229 230
    v8::Isolate::CreateParams params;
    params.enable_serializer = true;
    v8::Isolate* isolate = v8::Isolate::New(params);
    Serialize(isolate);
    Serialize(isolate);
231
  }
232 233 234
}


235 236 237
//----------------------------------------------------------------------------
// Tests that the heap can be deserialized.

238 239 240 241 242 243

static void ReserveSpaceForSnapshot(Deserializer* deserializer,
                                    const char* file_name) {
  int file_name_length = StrLength(file_name) + 10;
  Vector<char> name = Vector<char>::New(file_name_length + 1);
  SNPrintF(name, "%s.size", file_name);
244
  FILE* fp = v8::base::OS::FOpen(name.start(), "r");
245 246
  name.Dispose();
  int new_size, pointer_size, data_size, code_size, map_size, cell_size,
247
      property_cell_size, lo_size;
248
#if V8_CC_MSVC
249 250 251 252 253 254 255 256 257 258 259
  // Avoid warning about unsafe fscanf from MSVC.
  // Please note that this is only fine if %c and %s are not being used.
#define fscanf fscanf_s
#endif
  CHECK_EQ(1, fscanf(fp, "new %d\n", &new_size));
  CHECK_EQ(1, fscanf(fp, "pointer %d\n", &pointer_size));
  CHECK_EQ(1, fscanf(fp, "data %d\n", &data_size));
  CHECK_EQ(1, fscanf(fp, "code %d\n", &code_size));
  CHECK_EQ(1, fscanf(fp, "map %d\n", &map_size));
  CHECK_EQ(1, fscanf(fp, "cell %d\n", &cell_size));
  CHECK_EQ(1, fscanf(fp, "property cell %d\n", &property_cell_size));
260
  CHECK_EQ(1, fscanf(fp, "lo %d\n", &lo_size));
261
#if V8_CC_MSVC
262 263 264
#undef fscanf
#endif
  fclose(fp);
265 266 267 268 269 270 271 272
  deserializer->AddReservation(NEW_SPACE, new_size);
  deserializer->AddReservation(OLD_POINTER_SPACE, pointer_size);
  deserializer->AddReservation(OLD_DATA_SPACE, data_size);
  deserializer->AddReservation(CODE_SPACE, code_size);
  deserializer->AddReservation(MAP_SPACE, map_size);
  deserializer->AddReservation(CELL_SPACE, cell_size);
  deserializer->AddReservation(PROPERTY_CELL_SPACE, property_cell_size);
  deserializer->AddReservation(LO_SPACE, lo_size);
273 274 275
}


276
v8::Isolate* InitializeFromFile(const char* snapshot_file) {
277 278
  int len;
  byte* str = ReadBytes(snapshot_file, &len);
279 280
  if (!str) return NULL;
  v8::Isolate* v8_isolate = NULL;
281 282 283 284
  {
    SnapshotByteSource source(str, len);
    Deserializer deserializer(&source);
    ReserveSpaceForSnapshot(&deserializer, snapshot_file);
285 286 287 288
    Isolate* isolate = Isolate::NewForTesting();
    v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
    v8::Isolate::Scope isolate_scope(v8_isolate);
    isolate->Init(&deserializer);
289 290
  }
  DeleteArray(str);
291
  return v8_isolate;
292 293 294
}


295 296 297 298
static v8::Isolate* Deserialize() {
  v8::Isolate* isolate = InitializeFromFile(FLAG_testing_serialization_file);
  CHECK(isolate);
  return isolate;
299 300 301
}


302 303 304
static void SanityCheck(v8::Isolate* v8_isolate) {
  Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
  v8::HandleScope scope(v8_isolate);
305
#ifdef VERIFY_HEAP
306
  isolate->heap()->Verify();
307
#endif
308 309
  CHECK(isolate->global_object()->IsJSObject());
  CHECK(isolate->native_context()->IsContext());
310
  CHECK(isolate->heap()->string_table()->IsStringTable());
311
  isolate->factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("Empty"));
312 313 314
}


315
UNINITIALIZED_DEPENDENT_TEST(Deserialize, Serialize) {
316 317 318
  // The serialize-deserialize tests only work if the VM is built without
  // serialization.  That doesn't matter.  We don't need to be able to
  // serialize a snapshot in a VM that is booted from a snapshot.
319
  if (!Snapshot::HaveASnapshotToStartFrom()) {
320 321 322 323
    v8::Isolate* isolate = Deserialize();
    {
      v8::HandleScope handle_scope(isolate);
      v8::Isolate::Scope isolate_scope(isolate);
324

325 326
      v8::Local<v8::Context> env = v8::Context::New(isolate);
      env->Enter();
327

328 329 330
      SanityCheck(isolate);
    }
    isolate->Dispose();
331
  }
332 333 334
}


335 336
UNINITIALIZED_DEPENDENT_TEST(DeserializeFromSecondSerialization,
                             SerializeTwice) {
337
  if (!Snapshot::HaveASnapshotToStartFrom()) {
338 339 340 341
    v8::Isolate* isolate = Deserialize();
    {
      v8::Isolate::Scope isolate_scope(isolate);
      v8::HandleScope handle_scope(isolate);
342

343 344
      v8::Local<v8::Context> env = v8::Context::New(isolate);
      env->Enter();
345

346 347 348
      SanityCheck(isolate);
    }
    isolate->Dispose();
349
  }
350 351 352
}


353
UNINITIALIZED_DEPENDENT_TEST(DeserializeAndRunScript2, Serialize) {
354
  if (!Snapshot::HaveASnapshotToStartFrom()) {
355 356 357 358 359
    v8::Isolate* isolate = Deserialize();
    {
      v8::Isolate::Scope isolate_scope(isolate);
      v8::HandleScope handle_scope(isolate);

360

361 362
      v8::Local<v8::Context> env = v8::Context::New(isolate);
      env->Enter();
363

364 365 366 367 368 369
      const char* c_source = "\"1234\".length";
      v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, c_source);
      v8::Local<v8::Script> script = v8::Script::Compile(source);
      CHECK_EQ(4, script->Run()->Int32Value());
    }
    isolate->Dispose();
370
  }
371 372 373
}


374 375
UNINITIALIZED_DEPENDENT_TEST(DeserializeFromSecondSerializationAndRunScript2,
                             SerializeTwice) {
376
  if (!Snapshot::HaveASnapshotToStartFrom()) {
377 378 379 380
    v8::Isolate* isolate = Deserialize();
    {
      v8::Isolate::Scope isolate_scope(isolate);
      v8::HandleScope handle_scope(isolate);
381

382 383
      v8::Local<v8::Context> env = v8::Context::New(isolate);
      env->Enter();
384

385 386 387 388 389 390
      const char* c_source = "\"1234\".length";
      v8::Local<v8::String> source = v8::String::NewFromUtf8(isolate, c_source);
      v8::Local<v8::Script> script = v8::Script::Compile(source);
      CHECK_EQ(4, script->Run()->Int32Value());
    }
    isolate->Dispose();
391
  }
392 393 394
}


395
UNINITIALIZED_TEST(PartialSerialization) {
396
  if (!Snapshot::HaveASnapshotToStartFrom()) {
397 398 399 400 401
    v8::Isolate::CreateParams params;
    params.enable_serializer = true;
    v8::Isolate* v8_isolate = v8::Isolate::New(params);
    Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
    v8_isolate->Enter();
402
    {
403
      Heap* heap = isolate->heap();
404

405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
      v8::Persistent<v8::Context> env;
      {
        HandleScope scope(isolate);
        env.Reset(v8_isolate, v8::Context::New(v8_isolate));
      }
      DCHECK(!env.IsEmpty());
      {
        v8::HandleScope handle_scope(v8_isolate);
        v8::Local<v8::Context>::New(v8_isolate, env)->Enter();
      }
      // Make sure all builtin scripts are cached.
      {
        HandleScope scope(isolate);
        for (int i = 0; i < Natives::GetBuiltinsCount(); i++) {
          isolate->bootstrapper()->NativesSourceLookup(i);
        }
      }
      heap->CollectAllGarbage(Heap::kNoGCFlags);
      heap->CollectAllGarbage(Heap::kNoGCFlags);

      Object* raw_foo;
      {
        v8::HandleScope handle_scope(v8_isolate);
        v8::Local<v8::String> foo = v8::String::NewFromUtf8(v8_isolate, "foo");
        DCHECK(!foo.IsEmpty());
        raw_foo = *(v8::Utils::OpenHandle(*foo));
      }
432

433 434 435
      int file_name_length = StrLength(FLAG_testing_serialization_file) + 10;
      Vector<char> startup_name = Vector<char>::New(file_name_length + 1);
      SNPrintF(startup_name, "%s.startup", FLAG_testing_serialization_file);
436

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
      {
        v8::HandleScope handle_scope(v8_isolate);
        v8::Local<v8::Context>::New(v8_isolate, env)->Exit();
      }
      env.Reset();

      FileByteSink startup_sink(startup_name.start());
      StartupSerializer startup_serializer(isolate, &startup_sink);
      startup_serializer.SerializeStrongReferences();

      FileByteSink partial_sink(FLAG_testing_serialization_file);
      PartialSerializer p_ser(isolate, &startup_serializer, &partial_sink);
      p_ser.Serialize(&raw_foo);
      startup_serializer.SerializeWeakReferences();

452 453 454 455 456 457
      p_ser.FinalizeAllocation();
      startup_serializer.FinalizeAllocation();

      partial_sink.WriteSpaceUsed(&p_ser);

      startup_sink.WriteSpaceUsed(&startup_serializer);
458
      startup_name.Dispose();
459
    }
460 461
    v8_isolate->Exit();
    v8_isolate->Dispose();
462
  }
463 464 465
}


466
UNINITIALIZED_DEPENDENT_TEST(PartialDeserialization, PartialSerialization) {
467
  if (!Snapshot::HaveASnapshotToStartFrom()) {
468 469
    int file_name_length = StrLength(FLAG_testing_serialization_file) + 10;
    Vector<char> startup_name = Vector<char>::New(file_name_length + 1);
470
    SNPrintF(startup_name, "%s.startup", FLAG_testing_serialization_file);
471

472 473
    v8::Isolate* v8_isolate = InitializeFromFile(startup_name.start());
    CHECK(v8_isolate);
474
    startup_name.Dispose();
475
    {
476
      v8::Isolate::Scope isolate_scope(v8_isolate);
477

478
      const char* file_name = FLAG_testing_serialization_file;
479

480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
      int snapshot_size = 0;
      byte* snapshot = ReadBytes(file_name, &snapshot_size);

      Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
      Object* root;
      {
        SnapshotByteSource source(snapshot, snapshot_size);
        Deserializer deserializer(&source);
        ReserveSpaceForSnapshot(&deserializer, file_name);
        deserializer.DeserializePartial(isolate, &root);
        CHECK(root->IsString());
      }
      HandleScope handle_scope(isolate);
      Handle<Object> root_handle(root, isolate);


      Object* root2;
      {
        SnapshotByteSource source(snapshot, snapshot_size);
        Deserializer deserializer(&source);
        ReserveSpaceForSnapshot(&deserializer, file_name);
        deserializer.DeserializePartial(isolate, &root2);
        CHECK(root2->IsString());
        CHECK(*root_handle == root2);
      }
505
    }
506
    v8_isolate->Dispose();
507
  }
508
}
509

510

511
UNINITIALIZED_TEST(ContextSerialization) {
512
  if (!Snapshot::HaveASnapshotToStartFrom()) {
513 514 515 516
    v8::Isolate::CreateParams params;
    params.enable_serializer = true;
    v8::Isolate* v8_isolate = v8::Isolate::New(params);
    Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
517
    Heap* heap = isolate->heap();
518
    {
519 520 521 522 523 524
      v8::Isolate::Scope isolate_scope(v8_isolate);

      v8::Persistent<v8::Context> env;
      {
        HandleScope scope(isolate);
        env.Reset(v8_isolate, v8::Context::New(v8_isolate));
525
      }
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
      DCHECK(!env.IsEmpty());
      {
        v8::HandleScope handle_scope(v8_isolate);
        v8::Local<v8::Context>::New(v8_isolate, env)->Enter();
      }
      // Make sure all builtin scripts are cached.
      {
        HandleScope scope(isolate);
        for (int i = 0; i < Natives::GetBuiltinsCount(); i++) {
          isolate->bootstrapper()->NativesSourceLookup(i);
        }
      }
      // If we don't do this then we end up with a stray root pointing at the
      // context even after we have disposed of env.
      heap->CollectAllGarbage(Heap::kNoGCFlags);
541

542 543 544
      int file_name_length = StrLength(FLAG_testing_serialization_file) + 10;
      Vector<char> startup_name = Vector<char>::New(file_name_length + 1);
      SNPrintF(startup_name, "%s.startup", FLAG_testing_serialization_file);
545

546 547 548 549
      {
        v8::HandleScope handle_scope(v8_isolate);
        v8::Local<v8::Context>::New(v8_isolate, env)->Exit();
      }
550

551 552 553 554 555 556 557 558 559 560 561 562 563
      i::Object* raw_context = *v8::Utils::OpenPersistent(env);

      env.Reset();

      FileByteSink startup_sink(startup_name.start());
      StartupSerializer startup_serializer(isolate, &startup_sink);
      startup_serializer.SerializeStrongReferences();

      FileByteSink partial_sink(FLAG_testing_serialization_file);
      PartialSerializer p_ser(isolate, &startup_serializer, &partial_sink);
      p_ser.Serialize(&raw_context);
      startup_serializer.SerializeWeakReferences();

564 565 566 567 568 569
      p_ser.FinalizeAllocation();
      startup_serializer.FinalizeAllocation();

      partial_sink.WriteSpaceUsed(&p_ser);

      startup_sink.WriteSpaceUsed(&startup_serializer);
570 571 572
      startup_name.Dispose();
    }
    v8_isolate->Dispose();
573
  }
574 575 576
}


577
UNINITIALIZED_DEPENDENT_TEST(ContextDeserialization, ContextSerialization) {
578
  if (!Snapshot::HaveASnapshotToStartFrom()) {
579 580
    int file_name_length = StrLength(FLAG_testing_serialization_file) + 10;
    Vector<char> startup_name = Vector<char>::New(file_name_length + 1);
581
    SNPrintF(startup_name, "%s.startup", FLAG_testing_serialization_file);
582

583 584
    v8::Isolate* v8_isolate = InitializeFromFile(startup_name.start());
    CHECK(v8_isolate);
585
    startup_name.Dispose();
586
    {
587
      v8::Isolate::Scope isolate_scope(v8_isolate);
588

589
      const char* file_name = FLAG_testing_serialization_file;
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
      int snapshot_size = 0;
      byte* snapshot = ReadBytes(file_name, &snapshot_size);

      Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
      Object* root;
      {
        SnapshotByteSource source(snapshot, snapshot_size);
        Deserializer deserializer(&source);
        ReserveSpaceForSnapshot(&deserializer, file_name);
        deserializer.DeserializePartial(isolate, &root);
        CHECK(root->IsContext());
      }
      HandleScope handle_scope(isolate);
      Handle<Object> root_handle(root, isolate);


      Object* root2;
      {
        SnapshotByteSource source(snapshot, snapshot_size);
        Deserializer deserializer(&source);
        ReserveSpaceForSnapshot(&deserializer, file_name);
        deserializer.DeserializePartial(isolate, &root2);
        CHECK(root2->IsContext());
        CHECK(*root_handle != root2);
      }
616
    }
617
    v8_isolate->Dispose();
618
  }
619 620 621
}


622 623 624 625 626 627 628 629 630 631 632 633 634 635
TEST(TestThatAlwaysSucceeds) {
}


TEST(TestThatAlwaysFails) {
  bool ArtificialFailure = false;
  CHECK(ArtificialFailure);
}


DEPENDENT_TEST(DependentTestThatAlwaysFails, TestThatAlwaysSucceeds) {
  bool ArtificialFailure2 = false;
  CHECK(ArtificialFailure2);
}
636 637 638 639 640 641 642 643 644 645 646 647 648 649


int CountBuiltins() {
  // Check that we have not deserialized any additional builtin.
  HeapIterator iterator(CcTest::heap());
  DisallowHeapAllocation no_allocation;
  int counter = 0;
  for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
    if (obj->IsCode() && Code::cast(obj)->kind() == Code::BUILTIN) counter++;
  }
  return counter;
}


650
TEST(SerializeToplevelOnePlusOne) {
651
  FLAG_serialize_toplevel = true;
652
  LocalContext context;
653 654
  Isolate* isolate = CcTest::i_isolate();
  isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.
655

656
  v8::HandleScope scope(CcTest::isolate());
657

658
  const char* source = "1 + 1";
659

660 661 662 663 664 665 666 667
  Handle<String> orig_source = isolate->factory()
                                   ->NewStringFromUtf8(CStrVector(source))
                                   .ToHandleChecked();
  Handle<String> copy_source = isolate->factory()
                                   ->NewStringFromUtf8(CStrVector(source))
                                   .ToHandleChecked();
  CHECK(!orig_source.is_identical_to(copy_source));
  CHECK(orig_source->Equals(*copy_source));
668 669 670

  ScriptData* cache = NULL;

671 672 673 674
  Handle<SharedFunctionInfo> orig = Compiler::CompileScript(
      orig_source, Handle<String>(), 0, 0, false,
      Handle<Context>(isolate->native_context()), NULL, &cache,
      v8::ScriptCompiler::kProduceCodeCache, NOT_NATIVES_CODE);
675 676 677

  int builtins_count = CountBuiltins();

678 679 680
  Handle<SharedFunctionInfo> copy;
  {
    DisallowCompilation no_compile_expected(isolate);
681 682 683 684
    copy = Compiler::CompileScript(
        copy_source, Handle<String>(), 0, 0, false,
        Handle<Context>(isolate->native_context()), NULL, &cache,
        v8::ScriptCompiler::kConsumeCodeCache, NOT_NATIVES_CODE);
685
  }
686

687
  CHECK_NE(*orig, *copy);
688
  CHECK(Script::cast(copy->script())->source() == *copy_source);
689

690
  Handle<JSFunction> copy_fun =
691
      isolate->factory()->NewFunctionFromSharedFunctionInfo(
692
          copy, isolate->native_context());
693
  Handle<JSObject> global(isolate->context()->global_object());
694 695 696
  Handle<Object> copy_result =
      Execution::Call(isolate, copy_fun, global, 0, NULL).ToHandleChecked();
  CHECK_EQ(2, Handle<Smi>::cast(copy_result)->value());
697 698 699 700 701

  CHECK_EQ(builtins_count, CountBuiltins());

  delete cache;
}
702 703 704 705 706


TEST(SerializeToplevelInternalizedString) {
  FLAG_serialize_toplevel = true;
  LocalContext context;
707 708 709
  Isolate* isolate = CcTest::i_isolate();
  isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.

710 711
  v8::HandleScope scope(CcTest::isolate());

712
  const char* source = "'string1'";
713

714 715 716 717 718 719 720 721
  Handle<String> orig_source = isolate->factory()
                                   ->NewStringFromUtf8(CStrVector(source))
                                   .ToHandleChecked();
  Handle<String> copy_source = isolate->factory()
                                   ->NewStringFromUtf8(CStrVector(source))
                                   .ToHandleChecked();
  CHECK(!orig_source.is_identical_to(copy_source));
  CHECK(orig_source->Equals(*copy_source));
722 723 724 725

  Handle<JSObject> global(isolate->context()->global_object());
  ScriptData* cache = NULL;

726 727 728 729
  Handle<SharedFunctionInfo> orig = Compiler::CompileScript(
      orig_source, Handle<String>(), 0, 0, false,
      Handle<Context>(isolate->native_context()), NULL, &cache,
      v8::ScriptCompiler::kProduceCodeCache, NOT_NATIVES_CODE);
730 731 732 733 734 735 736 737 738
  Handle<JSFunction> orig_fun =
      isolate->factory()->NewFunctionFromSharedFunctionInfo(
          orig, isolate->native_context());
  Handle<Object> orig_result =
      Execution::Call(isolate, orig_fun, global, 0, NULL).ToHandleChecked();
  CHECK(orig_result->IsInternalizedString());

  int builtins_count = CountBuiltins();

739 740 741
  Handle<SharedFunctionInfo> copy;
  {
    DisallowCompilation no_compile_expected(isolate);
742 743 744 745
    copy = Compiler::CompileScript(
        copy_source, Handle<String>(), 0, 0, false,
        Handle<Context>(isolate->native_context()), NULL, &cache,
        v8::ScriptCompiler::kConsumeCodeCache, NOT_NATIVES_CODE);
746
  }
747
  CHECK_NE(*orig, *copy);
748
  CHECK(Script::cast(copy->script())->source() == *copy_source);
749

750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
  Handle<JSFunction> copy_fun =
      isolate->factory()->NewFunctionFromSharedFunctionInfo(
          copy, isolate->native_context());
  CHECK_NE(*orig_fun, *copy_fun);
  Handle<Object> copy_result =
      Execution::Call(isolate, copy_fun, global, 0, NULL).ToHandleChecked();
  CHECK(orig_result.is_identical_to(copy_result));
  Handle<String> expected =
      isolate->factory()->NewStringFromAsciiChecked("string1");

  CHECK(Handle<String>::cast(copy_result)->Equals(*expected));
  CHECK_EQ(builtins_count, CountBuiltins());

  delete cache;
}
765 766


767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
Vector<const uint8_t> ConstructSource(Vector<const uint8_t> head,
                                      Vector<const uint8_t> body,
                                      Vector<const uint8_t> tail, int repeats) {
  int source_length = head.length() + body.length() * repeats + tail.length();
  uint8_t* source = NewArray<uint8_t>(static_cast<size_t>(source_length));
  CopyChars(source, head.start(), head.length());
  for (int i = 0; i < repeats; i++) {
    CopyChars(source + head.length() + i * body.length(), body.start(),
              body.length());
  }
  CopyChars(source + head.length() + repeats * body.length(), tail.start(),
            tail.length());
  return Vector<const uint8_t>(const_cast<const uint8_t*>(source),
                               source_length);
}


TEST(SerializeToplevelLargeCodeObject) {
  FLAG_serialize_toplevel = true;
  LocalContext context;
  Isolate* isolate = CcTest::i_isolate();
  isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.

  v8::HandleScope scope(CcTest::isolate());

  Vector<const uint8_t> source =
      ConstructSource(STATIC_CHAR_VECTOR("var j=1; try { if (j) throw 1;"),
                      STATIC_CHAR_VECTOR("for(var i=0;i<1;i++)j++;"),
                      STATIC_CHAR_VECTOR("} catch (e) { j=7; } j"), 10000);
  Handle<String> source_str =
      isolate->factory()->NewStringFromOneByte(source).ToHandleChecked();

  Handle<JSObject> global(isolate->context()->global_object());
  ScriptData* cache = NULL;

  Handle<SharedFunctionInfo> orig = Compiler::CompileScript(
      source_str, Handle<String>(), 0, 0, false,
      Handle<Context>(isolate->native_context()), NULL, &cache,
      v8::ScriptCompiler::kProduceCodeCache, NOT_NATIVES_CODE);

  CHECK(isolate->heap()->InSpace(orig->code(), LO_SPACE));

  Handle<SharedFunctionInfo> copy;
  {
    DisallowCompilation no_compile_expected(isolate);
    copy = Compiler::CompileScript(
        source_str, Handle<String>(), 0, 0, false,
        Handle<Context>(isolate->native_context()), NULL, &cache,
        v8::ScriptCompiler::kConsumeCodeCache, NOT_NATIVES_CODE);
  }
  CHECK_NE(*orig, *copy);

  Handle<JSFunction> copy_fun =
      isolate->factory()->NewFunctionFromSharedFunctionInfo(
          copy, isolate->native_context());

  Handle<Object> copy_result =
      Execution::Call(isolate, copy_fun, global, 0, NULL).ToHandleChecked();

  int result_int;
  CHECK(copy_result->ToInt32(&result_int));
  CHECK_EQ(7, result_int);

  delete cache;
  source.Dispose();
}


TEST(SerializeToplevelLargeString) {
  FLAG_serialize_toplevel = true;
  LocalContext context;
  Isolate* isolate = CcTest::i_isolate();
  isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.

  v8::HandleScope scope(CcTest::isolate());

  Vector<const uint8_t> source = ConstructSource(
      STATIC_CHAR_VECTOR("var s = \""), STATIC_CHAR_VECTOR("abcdef"),
      STATIC_CHAR_VECTOR("\"; s"), 1000000);
  Handle<String> source_str =
      isolate->factory()->NewStringFromOneByte(source).ToHandleChecked();

  Handle<JSObject> global(isolate->context()->global_object());
  ScriptData* cache = NULL;

  Handle<SharedFunctionInfo> orig = Compiler::CompileScript(
      source_str, Handle<String>(), 0, 0, false,
      Handle<Context>(isolate->native_context()), NULL, &cache,
      v8::ScriptCompiler::kProduceCodeCache, NOT_NATIVES_CODE);

  Handle<SharedFunctionInfo> copy;
  {
    DisallowCompilation no_compile_expected(isolate);
    copy = Compiler::CompileScript(
        source_str, Handle<String>(), 0, 0, false,
        Handle<Context>(isolate->native_context()), NULL, &cache,
        v8::ScriptCompiler::kConsumeCodeCache, NOT_NATIVES_CODE);
  }
  CHECK_NE(*orig, *copy);

  Handle<JSFunction> copy_fun =
      isolate->factory()->NewFunctionFromSharedFunctionInfo(
          copy, isolate->native_context());

  Handle<Object> copy_result =
      Execution::Call(isolate, copy_fun, global, 0, NULL).ToHandleChecked();

  CHECK_EQ(6 * 1000000, Handle<String>::cast(copy_result)->length());
  CHECK(isolate->heap()->InSpace(HeapObject::cast(*copy_result), LO_SPACE));

  delete cache;
  source.Dispose();
}


882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
TEST(SerializeToplevelThreeBigStrings) {
  FLAG_serialize_toplevel = true;
  LocalContext context;
  Isolate* isolate = CcTest::i_isolate();
  Factory* f = isolate->factory();
  isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.

  v8::HandleScope scope(CcTest::isolate());

  Vector<const uint8_t> source_a =
      ConstructSource(STATIC_CHAR_VECTOR("var a = \""), STATIC_CHAR_VECTOR("a"),
                      STATIC_CHAR_VECTOR("\";"), 700000);
  Handle<String> source_a_str =
      f->NewStringFromOneByte(source_a).ToHandleChecked();

  Vector<const uint8_t> source_b =
      ConstructSource(STATIC_CHAR_VECTOR("var b = \""), STATIC_CHAR_VECTOR("b"),
                      STATIC_CHAR_VECTOR("\";"), 600000);
  Handle<String> source_b_str =
      f->NewStringFromOneByte(source_b).ToHandleChecked();

  Vector<const uint8_t> source_c =
      ConstructSource(STATIC_CHAR_VECTOR("var c = \""), STATIC_CHAR_VECTOR("c"),
                      STATIC_CHAR_VECTOR("\";"), 500000);
  Handle<String> source_c_str =
      f->NewStringFromOneByte(source_c).ToHandleChecked();

  Handle<String> source_str =
      f->NewConsString(
             f->NewConsString(source_a_str, source_b_str).ToHandleChecked(),
             source_c_str).ToHandleChecked();

  Handle<JSObject> global(isolate->context()->global_object());
  ScriptData* cache = NULL;

  Handle<SharedFunctionInfo> orig = Compiler::CompileScript(
      source_str, Handle<String>(), 0, 0, false,
      Handle<Context>(isolate->native_context()), NULL, &cache,
      v8::ScriptCompiler::kProduceCodeCache, NOT_NATIVES_CODE);

  Handle<SharedFunctionInfo> copy;
  {
    DisallowCompilation no_compile_expected(isolate);
    copy = Compiler::CompileScript(
        source_str, Handle<String>(), 0, 0, false,
        Handle<Context>(isolate->native_context()), NULL, &cache,
        v8::ScriptCompiler::kConsumeCodeCache, NOT_NATIVES_CODE);
  }
  CHECK_NE(*orig, *copy);

  Handle<JSFunction> copy_fun =
      isolate->factory()->NewFunctionFromSharedFunctionInfo(
          copy, isolate->native_context());

936
  USE(Execution::Call(isolate, copy_fun, global, 0, NULL));
937 938 939 940 941 942 943 944 945 946 947 948 949 950

  CHECK_EQ(600000 + 700000, CompileRun("(a + b).length")->Int32Value());
  CHECK_EQ(500000 + 600000, CompileRun("(b + c).length")->Int32Value());
  Heap* heap = isolate->heap();
  CHECK(heap->InSpace(*v8::Utils::OpenHandle(*CompileRun("a")->ToString()),
                      OLD_DATA_SPACE));
  CHECK(heap->InSpace(*v8::Utils::OpenHandle(*CompileRun("b")->ToString()),
                      OLD_DATA_SPACE));
  CHECK(heap->InSpace(*v8::Utils::OpenHandle(*CompileRun("c")->ToString()),
                      OLD_DATA_SPACE));

  delete cache;
  source_a.Dispose();
  source_b.Dispose();
951
  source_c.Dispose();
952 953 954
}


955 956
class SerializerOneByteResource
    : public v8::String::ExternalOneByteStringResource {
957
 public:
958
  SerializerOneByteResource(const char* data, size_t length)
959 960 961 962 963 964 965 966 967 968
      : data_(data), length_(length) {}
  virtual const char* data() const { return data_; }
  virtual size_t length() const { return length_; }

 private:
  const char* data_;
  size_t length_;
};


969
class SerializerTwoByteResource : public v8::String::ExternalStringResource {
970
 public:
971
  SerializerTwoByteResource(const char* data, size_t length)
972
      : data_(AsciiToTwoByteString(data)), length_(length) {}
973
  ~SerializerTwoByteResource() { DeleteArray<const uint16_t>(data_); }
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992

  virtual const uint16_t* data() const { return data_; }
  virtual size_t length() const { return length_; }

 private:
  const uint16_t* data_;
  size_t length_;
};


TEST(SerializeToplevelExternalString) {
  FLAG_serialize_toplevel = true;
  LocalContext context;
  Isolate* isolate = CcTest::i_isolate();
  isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.

  v8::HandleScope scope(CcTest::isolate());

  // Obtain external internalized one-byte string.
993
  SerializerOneByteResource one_byte_resource("one_byte", 8);
994 995 996 997 998 999 1000 1001
  Handle<String> one_byte_string =
      isolate->factory()->NewStringFromAsciiChecked("one_byte");
  one_byte_string = isolate->factory()->InternalizeString(one_byte_string);
  one_byte_string->MakeExternal(&one_byte_resource);
  CHECK(one_byte_string->IsExternalOneByteString());
  CHECK(one_byte_string->IsInternalizedString());

  // Obtain external internalized two-byte string.
1002
  SerializerTwoByteResource two_byte_resource("two_byte", 8);
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
  Handle<String> two_byte_string =
      isolate->factory()->NewStringFromAsciiChecked("two_byte");
  two_byte_string = isolate->factory()->InternalizeString(two_byte_string);
  two_byte_string->MakeExternal(&two_byte_resource);
  CHECK(two_byte_string->IsExternalTwoByteString());
  CHECK(two_byte_string->IsInternalizedString());

  const char* source =
      "var o = {}               \n"
      "o.one_byte = 7;          \n"
      "o.two_byte = 8;          \n"
      "o.one_byte + o.two_byte; \n";
  Handle<String> source_string = isolate->factory()
                                     ->NewStringFromUtf8(CStrVector(source))
                                     .ToHandleChecked();

  Handle<JSObject> global(isolate->context()->global_object());
  ScriptData* cache = NULL;

  Handle<SharedFunctionInfo> orig = Compiler::CompileScript(
      source_string, Handle<String>(), 0, 0, false,
      Handle<Context>(isolate->native_context()), NULL, &cache,
      v8::ScriptCompiler::kProduceCodeCache, NOT_NATIVES_CODE);

  Handle<SharedFunctionInfo> copy;
  {
    DisallowCompilation no_compile_expected(isolate);
    copy = Compiler::CompileScript(
        source_string, Handle<String>(), 0, 0, false,
        Handle<Context>(isolate->native_context()), NULL, &cache,
        v8::ScriptCompiler::kConsumeCodeCache, NOT_NATIVES_CODE);
  }
  CHECK_NE(*orig, *copy);

  Handle<JSFunction> copy_fun =
      isolate->factory()->NewFunctionFromSharedFunctionInfo(
          copy, isolate->native_context());

  Handle<Object> copy_result =
      Execution::Call(isolate, copy_fun, global, 0, NULL).ToHandleChecked();

  CHECK_EQ(15.0f, copy_result->Number());

  delete cache;
}


TEST(SerializeToplevelLargeExternalString) {
  FLAG_serialize_toplevel = true;
  LocalContext context;
  Isolate* isolate = CcTest::i_isolate();
  isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.

  Factory* f = isolate->factory();

  v8::HandleScope scope(CcTest::isolate());

  // Create a huge external internalized string to use as variable name.
  Vector<const uint8_t> string =
      ConstructSource(STATIC_CHAR_VECTOR(""), STATIC_CHAR_VECTOR("abcdef"),
                      STATIC_CHAR_VECTOR(""), 1000000);
  Handle<String> name = f->NewStringFromOneByte(string).ToHandleChecked();
1065
  SerializerOneByteResource one_byte_resource(
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
      reinterpret_cast<const char*>(string.start()), string.length());
  name = f->InternalizeString(name);
  name->MakeExternal(&one_byte_resource);
  CHECK(name->IsExternalOneByteString());
  CHECK(name->IsInternalizedString());
  CHECK(isolate->heap()->InSpace(*name, LO_SPACE));

  // Create the source, which is "var <literal> = 42; <literal>".
  Handle<String> source_str =
      f->NewConsString(
             f->NewConsString(f->NewStringFromAsciiChecked("var "), name)
                 .ToHandleChecked(),
             f->NewConsString(f->NewStringFromAsciiChecked(" = 42; "), name)
                 .ToHandleChecked()).ToHandleChecked();

  Handle<JSObject> global(isolate->context()->global_object());
  ScriptData* cache = NULL;

  Handle<SharedFunctionInfo> orig = Compiler::CompileScript(
      source_str, Handle<String>(), 0, 0, false,
      Handle<Context>(isolate->native_context()), NULL, &cache,
      v8::ScriptCompiler::kProduceCodeCache, NOT_NATIVES_CODE);

  Handle<SharedFunctionInfo> copy;
  {
    DisallowCompilation no_compile_expected(isolate);
    copy = Compiler::CompileScript(
        source_str, Handle<String>(), 0, 0, false,
        Handle<Context>(isolate->native_context()), NULL, &cache,
        v8::ScriptCompiler::kConsumeCodeCache, NOT_NATIVES_CODE);
  }
  CHECK_NE(*orig, *copy);

  Handle<JSFunction> copy_fun =
1100
      f->NewFunctionFromSharedFunctionInfo(copy, isolate->native_context());
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111

  Handle<Object> copy_result =
      Execution::Call(isolate, copy_fun, global, 0, NULL).ToHandleChecked();

  CHECK_EQ(42.0f, copy_result->Number());

  delete cache;
  string.Dispose();
}


1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
TEST(SerializeToplevelExternalScriptName) {
  FLAG_serialize_toplevel = true;
  LocalContext context;
  Isolate* isolate = CcTest::i_isolate();
  isolate->compilation_cache()->Disable();  // Disable same-isolate code cache.

  Factory* f = isolate->factory();

  v8::HandleScope scope(CcTest::isolate());

  const char* source =
      "var a = [1, 2, 3, 4];"
      "a.reduce(function(x, y) { return x + y }, 0)";

  Handle<String> source_string =
      f->NewStringFromUtf8(CStrVector(source)).ToHandleChecked();

  const SerializerOneByteResource one_byte_resource("one_byte", 8);
  Handle<String> name =
      f->NewExternalStringFromOneByte(&one_byte_resource).ToHandleChecked();
  CHECK(name->IsExternalOneByteString());
  CHECK(!name->IsInternalizedString());

  Handle<JSObject> global(isolate->context()->global_object());
  ScriptData* cache = NULL;

  Handle<SharedFunctionInfo> orig = Compiler::CompileScript(
      source_string, name, 0, 0, false,
      Handle<Context>(isolate->native_context()), NULL, &cache,
      v8::ScriptCompiler::kProduceCodeCache, NOT_NATIVES_CODE);

  Handle<SharedFunctionInfo> copy;
  {
    DisallowCompilation no_compile_expected(isolate);
    copy = Compiler::CompileScript(
        source_string, name, 0, 0, false,
        Handle<Context>(isolate->native_context()), NULL, &cache,
        v8::ScriptCompiler::kConsumeCodeCache, NOT_NATIVES_CODE);
  }
  CHECK_NE(*orig, *copy);

  Handle<JSFunction> copy_fun =
      f->NewFunctionFromSharedFunctionInfo(copy, isolate->native_context());

  Handle<Object> copy_result =
      Execution::Call(isolate, copy_fun, global, 0, NULL).ToHandleChecked();

  CHECK_EQ(10.0f, copy_result->Number());

  delete cache;
}


1165 1166 1167 1168 1169 1170
TEST(SerializeToplevelIsolates) {
  FLAG_serialize_toplevel = true;

  const char* source = "function f() { return 'abc'; }; f() + 'def'";
  v8::ScriptCompiler::CachedData* cache;

1171
  v8::Isolate* isolate1 = v8::Isolate::New();
1172
  {
1173 1174 1175
    v8::Isolate::Scope iscope(isolate1);
    v8::HandleScope scope(isolate1);
    v8::Local<v8::Context> context = v8::Context::New(isolate1);
1176 1177 1178 1179 1180 1181
    v8::Context::Scope context_scope(context);

    v8::Local<v8::String> source_str = v8_str(source);
    v8::ScriptOrigin origin(v8_str("test"));
    v8::ScriptCompiler::Source source(source_str, origin);
    v8::Local<v8::UnboundScript> script = v8::ScriptCompiler::CompileUnbound(
1182
        isolate1, &source, v8::ScriptCompiler::kProduceCodeCache);
1183
    const v8::ScriptCompiler::CachedData* data = source.GetCachedData();
1184
    CHECK(data);
1185 1186 1187 1188 1189 1190 1191 1192 1193
    // Persist cached data.
    uint8_t* buffer = NewArray<uint8_t>(data->length);
    MemCopy(buffer, data->data, data->length);
    cache = new v8::ScriptCompiler::CachedData(
        buffer, data->length, v8::ScriptCompiler::CachedData::BufferOwned);

    v8::Local<v8::Value> result = script->BindToCurrentContext()->Run();
    CHECK(result->ToString()->Equals(v8_str("abcdef")));
  }
1194
  isolate1->Dispose();
1195

1196
  v8::Isolate* isolate2 = v8::Isolate::New();
1197
  {
1198 1199 1200
    v8::Isolate::Scope iscope(isolate2);
    v8::HandleScope scope(isolate2);
    v8::Local<v8::Context> context = v8::Context::New(isolate2);
1201 1202 1203 1204 1205 1206 1207
    v8::Context::Scope context_scope(context);

    v8::Local<v8::String> source_str = v8_str(source);
    v8::ScriptOrigin origin(v8_str("test"));
    v8::ScriptCompiler::Source source(source_str, origin, cache);
    v8::Local<v8::UnboundScript> script;
    {
1208
      DisallowCompilation no_compile(reinterpret_cast<Isolate*>(isolate2));
1209
      script = v8::ScriptCompiler::CompileUnbound(
1210
          isolate2, &source, v8::ScriptCompiler::kConsumeCodeCache);
1211 1212 1213 1214
    }
    v8::Local<v8::Value> result = script->BindToCurrentContext()->Run();
    CHECK(result->ToString()->Equals(v8_str("abcdef")));
  }
1215
  isolate2->Dispose();
1216
}
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244


TEST(Bug3628) {
  FLAG_serialize_toplevel = true;
  FLAG_harmony_scoping = true;

  const char* source1 = "'use strict'; let x = 'X'";
  const char* source2 = "'use strict'; let y = 'Y'";
  const char* source3 = "'use strict'; x + y";

  v8::ScriptCompiler::CachedData* cache;

  v8::Isolate* isolate1 = v8::Isolate::New();
  {
    v8::Isolate::Scope iscope(isolate1);
    v8::HandleScope scope(isolate1);
    v8::Local<v8::Context> context = v8::Context::New(isolate1);
    v8::Context::Scope context_scope(context);

    CompileRun(source1);
    CompileRun(source2);

    v8::Local<v8::String> source_str = v8_str(source3);
    v8::ScriptOrigin origin(v8_str("test"));
    v8::ScriptCompiler::Source source(source_str, origin);
    v8::Local<v8::UnboundScript> script = v8::ScriptCompiler::CompileUnbound(
        isolate1, &source, v8::ScriptCompiler::kProduceCodeCache);
    const v8::ScriptCompiler::CachedData* data = source.GetCachedData();
1245
    CHECK(data);
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
    // Persist cached data.
    uint8_t* buffer = NewArray<uint8_t>(data->length);
    MemCopy(buffer, data->data, data->length);
    cache = new v8::ScriptCompiler::CachedData(
        buffer, data->length, v8::ScriptCompiler::CachedData::BufferOwned);

    v8::Local<v8::Value> result = script->BindToCurrentContext()->Run();
    CHECK(result->ToString()->Equals(v8_str("XY")));
  }
  isolate1->Dispose();

  v8::Isolate* isolate2 = v8::Isolate::New();
  {
    v8::Isolate::Scope iscope(isolate2);
    v8::HandleScope scope(isolate2);
    v8::Local<v8::Context> context = v8::Context::New(isolate2);
    v8::Context::Scope context_scope(context);

    // Reverse order of prior running scripts.
    CompileRun(source2);
    CompileRun(source1);

    v8::Local<v8::String> source_str = v8_str(source3);
    v8::ScriptOrigin origin(v8_str("test"));
    v8::ScriptCompiler::Source source(source_str, origin, cache);
    v8::Local<v8::UnboundScript> script;
    {
      DisallowCompilation no_compile(reinterpret_cast<Isolate*>(isolate2));
      script = v8::ScriptCompiler::CompileUnbound(
          isolate2, &source, v8::ScriptCompiler::kConsumeCodeCache);
    }
    v8::Local<v8::Value> result = script->BindToCurrentContext()->Run();
    CHECK(result->ToString()->Equals(v8_str("XY")));
  }
  isolate2->Dispose();
}