serialize.cc 57.2 KB
Newer Older
1
// Copyright 2006-2008 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 30 31 32 33 34 35 36 37 38 39 40
// 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 "v8.h"

#include "accessors.h"
#include "api.h"
#include "execution.h"
#include "global-handles.h"
#include "ic-inl.h"
#include "natives.h"
#include "platform.h"
#include "runtime.h"
#include "serialize.h"
#include "stub-cache.h"
#include "v8threads.h"
41
#include "top.h"
42
#include "bootstrapper.h"
43

44 45
namespace v8 {
namespace internal {
46

47

48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
// -----------------------------------------------------------------------------
// Coding of external references.

// The encoding of an external reference. The type is in the high word.
// The id is in the low word.
static uint32_t EncodeExternal(TypeCode type, uint16_t id) {
  return static_cast<uint32_t>(type) << 16 | id;
}


static int* GetInternalPointer(StatsCounter* counter) {
  // All counters refer to dummy_counter, if deserializing happens without
  // setting up counters.
  static int dummy_counter = 0;
  return counter->Enabled() ? counter->GetInternalPointer() : &dummy_counter;
}


// ExternalReferenceTable is a helper class that defines the relationship
// between external references and their encodings. It is used to build
// hashmaps in ExternalReferenceEncoder and ExternalReferenceDecoder.
class ExternalReferenceTable {
 public:
  static ExternalReferenceTable* instance() {
    if (!instance_) instance_ = new ExternalReferenceTable();
    return instance_;
  }

  int size() const { return refs_.length(); }

  Address address(int i) { return refs_[i].address; }

  uint32_t code(int i) { return refs_[i].code; }

  const char* name(int i) { return refs_[i].name; }

  int max_id(int code) { return max_id_[code]; }

 private:
  static ExternalReferenceTable* instance_;

89 90
  ExternalReferenceTable() : refs_(64) { PopulateTable(); }
  ~ExternalReferenceTable() { }
91 92 93 94 95 96 97

  struct ExternalReferenceEntry {
    Address address;
    uint32_t code;
    const char* name;
  };

98 99 100 101 102 103 104
  void PopulateTable();

  // For a few types of references, we can get their address from their id.
  void AddFromId(TypeCode type, uint16_t id, const char* name);

  // For other types of references, the caller will figure out the address.
  void Add(Address address, TypeCode type, uint16_t id, const char* name);
105 106 107 108 109 110 111 112 113

  List<ExternalReferenceEntry> refs_;
  int max_id_[kTypeCodeCount];
};


ExternalReferenceTable* ExternalReferenceTable::instance_ = NULL;


114 115 116 117 118
void ExternalReferenceTable::AddFromId(TypeCode type,
                                       uint16_t id,
                                       const char* name) {
  Address address;
  switch (type) {
119 120 121
    case C_BUILTIN: {
      ExternalReference ref(static_cast<Builtins::CFunctionId>(id));
      address = ref.address();
122
      break;
123 124 125 126
    }
    case BUILTIN: {
      ExternalReference ref(static_cast<Builtins::Name>(id));
      address = ref.address();
127
      break;
128 129 130 131
    }
    case RUNTIME_FUNCTION: {
      ExternalReference ref(static_cast<Runtime::FunctionId>(id));
      address = ref.address();
132
      break;
133 134 135 136
    }
    case IC_UTILITY: {
      ExternalReference ref(IC_Utility(static_cast<IC::UtilityId>(id)));
      address = ref.address();
137
      break;
138
    }
139 140 141 142 143 144 145 146 147 148 149 150
    default:
      UNREACHABLE();
      return;
  }
  Add(address, type, id, name);
}


void ExternalReferenceTable::Add(Address address,
                                 TypeCode type,
                                 uint16_t id,
                                 const char* name) {
151
  ASSERT_NE(NULL, address);
152 153 154 155
  ExternalReferenceEntry entry;
  entry.address = address;
  entry.code = EncodeExternal(type, id);
  entry.name = name;
156
  ASSERT_NE(0, entry.code);
157 158 159 160 161 162
  refs_.Add(entry);
  if (id > max_id_[type]) max_id_[type] = id;
}


void ExternalReferenceTable::PopulateTable() {
163 164 165 166
  for (int type_code = 0; type_code < kTypeCodeCount; type_code++) {
    max_id_[type_code] = 0;
  }

167 168 169 170 171 172 173 174 175 176 177 178 179
  // The following populates all of the different type of external references
  // into the ExternalReferenceTable.
  //
  // NOTE: This function was originally 100k of code.  It has since been
  // rewritten to be mostly table driven, as the callback macro style tends to
  // very easily cause code bloat.  Please be careful in the future when adding
  // new references.

  struct RefTableEntry {
    TypeCode type;
    uint16_t id;
    const char* name;
  };
180

181
  static const RefTableEntry ref_table[] = {
182
  // Builtins
183
#define DEF_ENTRY_C(name, ignored) \
184 185 186
  { C_BUILTIN, \
    Builtins::c_##name, \
    "Builtins::" #name },
187 188 189 190

  BUILTIN_LIST_C(DEF_ENTRY_C)
#undef DEF_ENTRY_C

191
#define DEF_ENTRY_C(name, ignored) \
192 193 194
  { BUILTIN, \
    Builtins::name, \
    "Builtins::" #name },
195
#define DEF_ENTRY_A(name, kind, state) DEF_ENTRY_C(name, ignored)
196 197 198

  BUILTIN_LIST_C(DEF_ENTRY_C)
  BUILTIN_LIST_A(DEF_ENTRY_A)
199
  BUILTIN_LIST_DEBUG_A(DEF_ENTRY_A)
200 201 202 203
#undef DEF_ENTRY_C
#undef DEF_ENTRY_A

  // Runtime functions
204
#define RUNTIME_ENTRY(name, nargs, ressize) \
205 206 207
  { RUNTIME_FUNCTION, \
    Runtime::k##name, \
    "Runtime::" #name },
208 209 210 211 212 213

  RUNTIME_FUNCTION_LIST(RUNTIME_ENTRY)
#undef RUNTIME_ENTRY

  // IC utilities
#define IC_ENTRY(name) \
214 215 216
  { IC_UTILITY, \
    IC::k##name, \
    "IC::" #name },
217 218 219

  IC_UTIL_LIST(IC_ENTRY)
#undef IC_ENTRY
220 221 222 223 224
  };  // end of ref_table[].

  for (size_t i = 0; i < ARRAY_SIZE(ref_table); ++i) {
    AddFromId(ref_table[i].type, ref_table[i].id, ref_table[i].name);
  }
225

226
#ifdef ENABLE_DEBUGGER_SUPPORT
227 228 229 230 231
  // Debug addresses
  Add(Debug_Address(Debug::k_after_break_target_address).address(),
      DEBUG_ADDRESS,
      Debug::k_after_break_target_address << kDebugIdShift,
      "Debug::after_break_target_address()");
232 233 234 235
  Add(Debug_Address(Debug::k_debug_break_slot_address).address(),
      DEBUG_ADDRESS,
      Debug::k_debug_break_slot_address << kDebugIdShift,
      "Debug::debug_break_slot_address()");
236 237 238 239
  Add(Debug_Address(Debug::k_debug_break_return_address).address(),
      DEBUG_ADDRESS,
      Debug::k_debug_break_return_address << kDebugIdShift,
      "Debug::debug_break_return_address()");
240 241 242 243
  Add(Debug_Address(Debug::k_restarter_frame_function_pointer).address(),
      DEBUG_ADDRESS,
      Debug::k_restarter_frame_function_pointer << kDebugIdShift,
      "Debug::restarter_frame_function_pointer_address()");
244
#endif
245 246

  // Stat counters
247 248 249 250 251 252 253
  struct StatsRefTableEntry {
    StatsCounter* counter;
    uint16_t id;
    const char* name;
  };

  static const StatsRefTableEntry stats_ref_table[] = {
254
#define COUNTER_ENTRY(name, caption) \
255 256 257
  { &Counters::name, \
    Counters::k_##name, \
    "Counters::" #name },
258 259 260 261

  STATS_COUNTER_LIST_1(COUNTER_ENTRY)
  STATS_COUNTER_LIST_2(COUNTER_ENTRY)
#undef COUNTER_ENTRY
262 263 264 265 266 267 268 269 270
  };  // end of stats_ref_table[].

  for (size_t i = 0; i < ARRAY_SIZE(stats_ref_table); ++i) {
    Add(reinterpret_cast<Address>(
            GetInternalPointer(stats_ref_table[i].counter)),
        STATS_COUNTER,
        stats_ref_table[i].id,
        stats_ref_table[i].name);
  }
271 272

  // Top addresses
273 274 275 276 277 278 279 280 281 282
  const char* top_address_format = "Top::%s";

  const char* AddressNames[] = {
#define C(name) #name,
    TOP_ADDRESS_LIST(C)
    TOP_ADDRESS_LIST_PROF(C)
    NULL
#undef C
  };

283
  int top_format_length = StrLength(top_address_format) - 2;
284
  for (uint16_t i = 0; i < Top::k_top_address_count; ++i) {
285 286
    const char* address_name = AddressNames[i];
    Vector<char> name =
287
        Vector<char>::New(top_format_length + StrLength(address_name) + 1);
288
    const char* chars = name.start();
289
    OS::SNPrintF(name, top_address_format, address_name);
290
    Add(Top::get_address_from_id((Top::AddressId)i), TOP_ADDRESS, i, chars);
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
  }

  // Accessors
#define ACCESSOR_DESCRIPTOR_DECLARATION(name) \
  Add((Address)&Accessors::name, \
      ACCESSOR, \
      Accessors::k##name, \
      "Accessors::" #name);

  ACCESSOR_DESCRIPTOR_LIST(ACCESSOR_DESCRIPTOR_DECLARATION)
#undef ACCESSOR_DESCRIPTOR_DECLARATION

  // Stub cache tables
  Add(SCTableReference::keyReference(StubCache::kPrimary).address(),
      STUB_CACHE_TABLE,
      1,
      "StubCache::primary_->key");
  Add(SCTableReference::valueReference(StubCache::kPrimary).address(),
      STUB_CACHE_TABLE,
      2,
      "StubCache::primary_->value");
  Add(SCTableReference::keyReference(StubCache::kSecondary).address(),
      STUB_CACHE_TABLE,
      3,
      "StubCache::secondary_->key");
  Add(SCTableReference::valueReference(StubCache::kSecondary).address(),
      STUB_CACHE_TABLE,
      4,
      "StubCache::secondary_->value");

  // Runtime entries
322
  Add(ExternalReference::perform_gc_function().address(),
323 324 325
      RUNTIME_ENTRY,
      1,
      "Runtime::PerformGC");
326
  Add(ExternalReference::fill_heap_number_with_random_function().address(),
327 328
      RUNTIME_ENTRY,
      2,
329
      "V8::FillHeapNumberWithRandom");
330

331 332 333 334 335
  Add(ExternalReference::random_uint32_function().address(),
      RUNTIME_ENTRY,
      3,
      "V8::Random");

336 337 338 339 340
  Add(ExternalReference::delete_handle_scope_extensions().address(),
      RUNTIME_ENTRY,
      3,
      "HandleScope::DeleteExtensions");

341 342 343 344 345
  // Miscellaneous
  Add(ExternalReference::the_hole_value_location().address(),
      UNCLASSIFIED,
      2,
      "Factory::the_hole_value().location()");
346
  Add(ExternalReference::roots_address().address(),
347
      UNCLASSIFIED,
348
      3,
349
      "Heap::roots_address()");
350
  Add(ExternalReference::address_of_stack_limit().address(),
351 352
      UNCLASSIFIED,
      4,
353
      "StackGuard::address_of_jslimit()");
354
  Add(ExternalReference::address_of_real_stack_limit().address(),
355
      UNCLASSIFIED,
356
      5,
357
      "StackGuard::address_of_real_jslimit()");
358
#ifndef V8_INTERPRETED_REGEXP
359 360 361
  Add(ExternalReference::address_of_regexp_stack_limit().address(),
      UNCLASSIFIED,
      6,
362
      "RegExpStack::limit_address()");
363
  Add(ExternalReference::address_of_regexp_stack_memory_address().address(),
364
      UNCLASSIFIED,
365
      7,
366 367 368 369 370 371 372 373 374
      "RegExpStack::memory_address()");
  Add(ExternalReference::address_of_regexp_stack_memory_size().address(),
      UNCLASSIFIED,
      8,
      "RegExpStack::memory_size()");
  Add(ExternalReference::address_of_static_offsets_vector().address(),
      UNCLASSIFIED,
      9,
      "OffsetsVector::static_offsets_vector");
375
#endif  // V8_INTERPRETED_REGEXP
376 377 378
  Add(ExternalReference::new_space_start().address(),
      UNCLASSIFIED,
      10,
379
      "Heap::NewSpaceStart()");
380
  Add(ExternalReference::new_space_mask().address(),
381
      UNCLASSIFIED,
382
      11,
383 384 385
      "Heap::NewSpaceMask()");
  Add(ExternalReference::heap_always_allocate_scope_depth().address(),
      UNCLASSIFIED,
386
      12,
387 388 389
      "Heap::always_allocate_scope_depth()");
  Add(ExternalReference::new_space_allocation_limit_address().address(),
      UNCLASSIFIED,
390
      13,
391 392 393
      "Heap::NewSpaceAllocationLimitAddress()");
  Add(ExternalReference::new_space_allocation_top_address().address(),
      UNCLASSIFIED,
394
      14,
395
      "Heap::NewSpaceAllocationTopAddress()");
396 397 398
#ifdef ENABLE_DEBUGGER_SUPPORT
  Add(ExternalReference::debug_break().address(),
      UNCLASSIFIED,
399
      15,
400
      "Debug::Break()");
401 402
  Add(ExternalReference::debug_step_in_fp_address().address(),
      UNCLASSIFIED,
403
      16,
404
      "Debug::step_in_fp_addr()");
405
#endif
406 407
  Add(ExternalReference::double_fp_operation(Token::ADD).address(),
      UNCLASSIFIED,
408
      17,
409 410 411
      "add_two_doubles");
  Add(ExternalReference::double_fp_operation(Token::SUB).address(),
      UNCLASSIFIED,
412
      18,
413 414 415
      "sub_two_doubles");
  Add(ExternalReference::double_fp_operation(Token::MUL).address(),
      UNCLASSIFIED,
416
      19,
417
      "mul_two_doubles");
418
  Add(ExternalReference::double_fp_operation(Token::DIV).address(),
419
      UNCLASSIFIED,
420
      20,
421 422 423
      "div_two_doubles");
  Add(ExternalReference::double_fp_operation(Token::MOD).address(),
      UNCLASSIFIED,
424
      21,
425 426 427
      "mod_two_doubles");
  Add(ExternalReference::compare_doubles().address(),
      UNCLASSIFIED,
428
      22,
429
      "compare_doubles");
430
#ifndef V8_INTERPRETED_REGEXP
lrn@chromium.org's avatar
lrn@chromium.org committed
431 432
  Add(ExternalReference::re_case_insensitive_compare_uc16().address(),
      UNCLASSIFIED,
433
      23,
lrn@chromium.org's avatar
lrn@chromium.org committed
434 435 436
      "NativeRegExpMacroAssembler::CaseInsensitiveCompareUC16()");
  Add(ExternalReference::re_check_stack_guard_state().address(),
      UNCLASSIFIED,
437
      24,
lrn@chromium.org's avatar
lrn@chromium.org committed
438 439 440
      "RegExpMacroAssembler*::CheckStackGuardState()");
  Add(ExternalReference::re_grow_stack().address(),
      UNCLASSIFIED,
441
      25,
lrn@chromium.org's avatar
lrn@chromium.org committed
442
      "NativeRegExpMacroAssembler::GrowStack()");
443 444
  Add(ExternalReference::re_word_character_map().address(),
      UNCLASSIFIED,
445
      26,
446
      "NativeRegExpMacroAssembler::word_character_map");
447
#endif  // V8_INTERPRETED_REGEXP
448 449 450
  // Keyed lookup cache.
  Add(ExternalReference::keyed_lookup_cache_keys().address(),
      UNCLASSIFIED,
451
      27,
452 453 454
      "KeyedLookupCache::keys()");
  Add(ExternalReference::keyed_lookup_cache_field_offsets().address(),
      UNCLASSIFIED,
455
      28,
456
      "KeyedLookupCache::field_offsets()");
457 458
  Add(ExternalReference::transcendental_cache_array_address().address(),
      UNCLASSIFIED,
459
      29,
460
      "TranscendentalCache::caches()");
461 462 463 464 465 466 467 468 469 470 471 472
  Add(ExternalReference::handle_scope_next_address().address(),
      UNCLASSIFIED,
      30,
      "HandleScope::next");
  Add(ExternalReference::handle_scope_limit_address().address(),
      UNCLASSIFIED,
      31,
      "HandleScope::limit");
  Add(ExternalReference::handle_scope_level_address().address(),
      UNCLASSIFIED,
      32,
      "HandleScope::level");
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
  Add(ExternalReference::new_deoptimizer_function().address(),
      UNCLASSIFIED,
      33,
      "Deoptimizer::New()");
  Add(ExternalReference::compute_output_frames_function().address(),
      UNCLASSIFIED,
      34,
      "Deoptimizer::ComputeOutputFrames()");
  Add(ExternalReference::address_of_min_int().address(),
      UNCLASSIFIED,
      35,
      "LDoubleConstant::min_int");
  Add(ExternalReference::address_of_one_half().address(),
      UNCLASSIFIED,
      36,
      "LDoubleConstant::one_half");
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
}


ExternalReferenceEncoder::ExternalReferenceEncoder()
    : encodings_(Match) {
  ExternalReferenceTable* external_references =
      ExternalReferenceTable::instance();
  for (int i = 0; i < external_references->size(); ++i) {
    Put(external_references->address(i), i);
  }
}


uint32_t ExternalReferenceEncoder::Encode(Address key) const {
  int index = IndexOf(key);
504
  ASSERT(key == NULL || index >= 0);
505 506 507 508 509 510 511 512 513 514 515 516 517 518
  return index >=0 ? ExternalReferenceTable::instance()->code(index) : 0;
}


const char* ExternalReferenceEncoder::NameOfAddress(Address key) const {
  int index = IndexOf(key);
  return index >=0 ? ExternalReferenceTable::instance()->name(index) : NULL;
}


int ExternalReferenceEncoder::IndexOf(Address key) const {
  if (key == NULL) return -1;
  HashMap::Entry* entry =
      const_cast<HashMap &>(encodings_).Lookup(key, Hash(key), false);
519 520 521
  return entry == NULL
      ? -1
      : static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
522 523 524 525 526
}


void ExternalReferenceEncoder::Put(Address key, int index) {
  HashMap::Entry* entry = encodings_.Lookup(key, Hash(key), true);
527
  entry->value = reinterpret_cast<void*>(index);
528 529 530 531
}


ExternalReferenceDecoder::ExternalReferenceDecoder()
532
    : encodings_(NewArray<Address*>(kTypeCodeCount)) {
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
  ExternalReferenceTable* external_references =
      ExternalReferenceTable::instance();
  for (int type = kFirstTypeCode; type < kTypeCodeCount; ++type) {
    int max = external_references->max_id(type) + 1;
    encodings_[type] = NewArray<Address>(max + 1);
  }
  for (int i = 0; i < external_references->size(); ++i) {
    Put(external_references->code(i), external_references->address(i));
  }
}


ExternalReferenceDecoder::~ExternalReferenceDecoder() {
  for (int type = kFirstTypeCode; type < kTypeCodeCount; ++type) {
    DeleteArray(encodings_[type]);
  }
  DeleteArray(encodings_);
}


553
bool Serializer::serialization_enabled_ = false;
554
bool Serializer::too_late_to_enable_now_ = false;
555
ExternalReferenceDecoder* Deserializer::external_reference_decoder_ = NULL;
556 557


558
Deserializer::Deserializer(SnapshotByteSource* source) : source_(source) {
559 560 561 562 563 564
}


// This routine both allocates a new object, and also keeps
// track of where objects have been allocated so that we can
// fix back references when deserializing.
565
Address Deserializer::Allocate(int space_index, Space* space, int size) {
566 567 568 569
  Address address;
  if (!SpaceIsLarge(space_index)) {
    ASSERT(!SpaceIsPaged(space_index) ||
           size <= Page::kPageSize - Page::kObjectStartOffset);
570
    MaybeObject* maybe_new_allocation;
571
    if (space_index == NEW_SPACE) {
572 573
      maybe_new_allocation =
          reinterpret_cast<NewSpace*>(space)->AllocateRaw(size);
574
    } else {
575 576
      maybe_new_allocation =
          reinterpret_cast<PagedSpace*>(space)->AllocateRaw(size);
577
    }
578
    Object* new_allocation = maybe_new_allocation->ToObjectUnchecked();
579 580 581 582 583
    HeapObject* new_object = HeapObject::cast(new_allocation);
    address = new_object->address();
    high_water_[space_index] = address + size;
  } else {
    ASSERT(SpaceIsLarge(space_index));
584
    ASSERT(size > Page::kPageSize - Page::kObjectStartOffset);
585
    LargeObjectSpace* lo_space = reinterpret_cast<LargeObjectSpace*>(space);
586 587
    Object* new_allocation;
    if (space_index == kLargeData) {
588
      new_allocation = lo_space->AllocateRaw(size)->ToObjectUnchecked();
589
    } else if (space_index == kLargeFixedArray) {
590 591
      new_allocation =
          lo_space->AllocateRawFixedArray(size)->ToObjectUnchecked();
592
    } else {
593
      ASSERT_EQ(kLargeCode, space_index);
594
      new_allocation = lo_space->AllocateRawCode(size)->ToObjectUnchecked();
595
    }
596 597 598
    HeapObject* new_object = HeapObject::cast(new_allocation);
    // Record all large objects in the same space.
    address = new_object->address();
599
    pages_[LO_SPACE].Add(address);
600
  }
601
  last_object_address_ = address;
602 603 604 605 606 607
  return address;
}


// This returns the address of an object that has been described in the
// snapshot as being offset bytes back in a particular space.
608
HeapObject* Deserializer::GetAddressFromEnd(int space) {
609 610 611 612 613 614 615 616 617
  int offset = source_->GetInt();
  ASSERT(!SpaceIsLarge(space));
  offset <<= kObjectAlignmentBits;
  return HeapObject::FromAddress(high_water_[space] - offset);
}


// This returns the address of an object that has been described in the
// snapshot as being offset bytes into a particular space.
618
HeapObject* Deserializer::GetAddressFromStart(int space) {
619 620 621
  int offset = source_->GetInt();
  if (SpaceIsLarge(space)) {
    // Large spaces have one object per 'page'.
622
    return HeapObject::FromAddress(pages_[LO_SPACE][offset]);
623 624 625 626
  }
  offset <<= kObjectAlignmentBits;
  if (space == NEW_SPACE) {
    // New space has only one space - numbered 0.
627
    return HeapObject::FromAddress(pages_[space][0] + offset);
628 629
  }
  ASSERT(SpaceIsPaged(space));
630
  int page_of_pointee = offset >> kPageSizeBits;
631
  Address object_address = pages_[space][page_of_pointee] +
632
                           (offset & Page::kPageAlignmentMask);
633 634 635 636
  return HeapObject::FromAddress(object_address);
}


637
void Deserializer::Deserialize() {
638 639 640 641 642 643 644 645
  // Don't GC while deserializing - just expand the heap.
  AlwaysAllocateScope always_allocate;
  // Don't use the free lists while deserializing.
  LinearAllocationScope allocate_linearly;
  // No active threads.
  ASSERT_EQ(NULL, ThreadState::FirstInUse());
  // No active handles.
  ASSERT(HandleScopeImplementer::instance()->blocks()->is_empty());
646 647 648
  // Make sure the entire partial snapshot cache is traversed, filling it with
  // valid object pointers.
  partial_snapshot_cache_length_ = kPartialSnapshotCacheCapacity;
649
  ASSERT_EQ(NULL, external_reference_decoder_);
650
  external_reference_decoder_ = new ExternalReferenceDecoder();
651 652
  Heap::IterateStrongRoots(this, VISIT_ONLY_STRONG);
  Heap::IterateWeakRoots(this, VISIT_ALL);
653 654

  Heap::set_global_contexts_list(Heap::undefined_value());
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
}


void Deserializer::DeserializePartial(Object** root) {
  // Don't GC while deserializing - just expand the heap.
  AlwaysAllocateScope always_allocate;
  // Don't use the free lists while deserializing.
  LinearAllocationScope allocate_linearly;
  if (external_reference_decoder_ == NULL) {
    external_reference_decoder_ = new ExternalReferenceDecoder();
  }
  VisitPointer(root);
}


670 671
Deserializer::~Deserializer() {
  ASSERT(source_->AtEOF());
672 673 674 675
  if (external_reference_decoder_ != NULL) {
    delete external_reference_decoder_;
    external_reference_decoder_ = NULL;
  }
676 677 678 679
}


// This is called on the roots.  It is the driver of the deserialization
680
// process.  It is also called on the body of each function.
681
void Deserializer::VisitPointers(Object** start, Object** end) {
682 683 684
  // The space must be new space.  Any other space would cause ReadChunk to try
  // to update the remembered using NULL as the address.
  ReadChunk(start, end, NEW_SPACE, NULL);
685 686 687 688 689 690 691 692 693
}


// This routine writes the new object into the pointer provided and then
// returns true if the new object was in young space and false otherwise.
// The reason for this strange interface is that otherwise the object is
// written very late, which means the ByteArray map is not set up by the
// time we need to use it to mark the space at the end of a page free (by
// making it into a byte array).
694 695 696
void Deserializer::ReadObject(int space_number,
                              Space* space,
                              Object** write_back) {
697
  int size = source_->GetInt() << kObjectAlignmentBits;
698
  Address address = Allocate(space_number, space, size);
699 700 701
  *write_back = HeapObject::FromAddress(address);
  Object** current = reinterpret_cast<Object**>(address);
  Object** limit = current + (size >> kPointerSizeLog2);
702 703 704
  if (FLAG_log_snapshot_positions) {
    LOG(SnapshotPositionEvent(address, source_->position()));
  }
705 706 707 708
  ReadChunk(current, limit, space_number, address);
}


709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
// This macro is always used with a constant argument so it should all fold
// away to almost nothing in the generated code.  It might be nicer to do this
// with the ternary operator but there are type issues with that.
#define ASSIGN_DEST_SPACE(space_number)                                        \
  Space* dest_space;                                                           \
  if (space_number == NEW_SPACE) {                                             \
    dest_space = Heap::new_space();                                            \
  } else if (space_number == OLD_POINTER_SPACE) {                              \
    dest_space = Heap::old_pointer_space();                                    \
  } else if (space_number == OLD_DATA_SPACE) {                                 \
    dest_space = Heap::old_data_space();                                       \
  } else if (space_number == CODE_SPACE) {                                     \
    dest_space = Heap::code_space();                                           \
  } else if (space_number == MAP_SPACE) {                                      \
    dest_space = Heap::map_space();                                            \
  } else if (space_number == CELL_SPACE) {                                     \
    dest_space = Heap::cell_space();                                           \
  } else {                                                                     \
    ASSERT(space_number >= LO_SPACE);                                          \
    dest_space = Heap::lo_space();                                             \
  }


static const int kUnknownOffsetFromStart = -1;
733 734


735 736
void Deserializer::ReadChunk(Object** current,
                             Object** limit,
737
                             int source_space,
738
                             Address address) {
739
  while (current < limit) {
740
    int data = source_->Get();
741
    switch (data) {
742 743 744 745
#define CASE_STATEMENT(where, how, within, space_number)                       \
      case where + how + within + space_number:                                \
      ASSERT((where & ~kPointedToMask) == 0);                                  \
      ASSERT((how & ~kHowToCodeMask) == 0);                                    \
746
      ASSERT((within & ~kWhereToPointMask) == 0);                              \
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
      ASSERT((space_number & ~kSpaceMask) == 0);

#define CASE_BODY(where, how, within, space_number_if_any, offset_from_start)  \
      {                                                                        \
        bool emit_write_barrier = false;                                       \
        bool current_was_incremented = false;                                  \
        int space_number =  space_number_if_any == kAnyOldSpace ?              \
                            (data & kSpaceMask) : space_number_if_any;         \
        if (where == kNewObject && how == kPlain && within == kStartOfObject) {\
          ASSIGN_DEST_SPACE(space_number)                                      \
          ReadObject(space_number, dest_space, current);                       \
          emit_write_barrier =                                                 \
            (space_number == NEW_SPACE && source_space != NEW_SPACE);          \
        } else {                                                               \
          Object* new_object = NULL;  /* May not be a real Object pointer. */  \
          if (where == kNewObject) {                                           \
            ASSIGN_DEST_SPACE(space_number)                                    \
            ReadObject(space_number, dest_space, &new_object);                 \
          } else if (where == kRootArray) {                                    \
            int root_id = source_->GetInt();                                   \
            new_object = Heap::roots_address()[root_id];                       \
          } else if (where == kPartialSnapshotCache) {                         \
            int cache_index = source_->GetInt();                               \
            new_object = partial_snapshot_cache_[cache_index];                 \
          } else if (where == kExternalReference) {                            \
            int reference_id = source_->GetInt();                              \
            Address address =                                                  \
                external_reference_decoder_->Decode(reference_id);             \
            new_object = reinterpret_cast<Object*>(address);                   \
          } else if (where == kBackref) {                                      \
            emit_write_barrier =                                               \
              (space_number == NEW_SPACE && source_space != NEW_SPACE);        \
            new_object = GetAddressFromEnd(data & kSpaceMask);                 \
          } else {                                                             \
            ASSERT(where == kFromStart);                                       \
            if (offset_from_start == kUnknownOffsetFromStart) {                \
              emit_write_barrier =                                             \
                (space_number == NEW_SPACE && source_space != NEW_SPACE);      \
              new_object = GetAddressFromStart(data & kSpaceMask);             \
            } else {                                                           \
              Address object_address = pages_[space_number][0] +               \
                  (offset_from_start << kObjectAlignmentBits);                 \
              new_object = HeapObject::FromAddress(object_address);            \
            }                                                                  \
          }                                                                    \
          if (within == kFirstInstruction) {                                   \
            Code* new_code_object = reinterpret_cast<Code*>(new_object);       \
            new_object = reinterpret_cast<Object*>(                            \
                new_code_object->instruction_start());                         \
          }                                                                    \
          if (how == kFromCode) {                                              \
            Address location_of_branch_data =                                  \
                reinterpret_cast<Address>(current);                            \
            Assembler::set_target_at(location_of_branch_data,                  \
                                     reinterpret_cast<Address>(new_object));   \
            if (within == kFirstInstruction) {                                 \
              location_of_branch_data += Assembler::kCallTargetSize;           \
              current = reinterpret_cast<Object**>(location_of_branch_data);   \
              current_was_incremented = true;                                  \
            }                                                                  \
          } else {                                                             \
            *current = new_object;                                             \
          }                                                                    \
        }                                                                      \
        if (emit_write_barrier) {                                              \
          Heap::RecordWrite(address, static_cast<int>(                         \
              reinterpret_cast<Address>(current) - address));                  \
        }                                                                      \
        if (!current_was_incremented) {                                        \
          current++;   /* Increment current if it wasn't done above. */        \
        }                                                                      \
        break;                                                                 \
      }                                                                        \

// This generates a case and a body for each space.  The large object spaces are
// very rare in snapshots so they are grouped in one body.
#define ONE_PER_SPACE(where, how, within)                                      \
  CASE_STATEMENT(where, how, within, NEW_SPACE)                                \
  CASE_BODY(where, how, within, NEW_SPACE, kUnknownOffsetFromStart)            \
  CASE_STATEMENT(where, how, within, OLD_DATA_SPACE)                           \
  CASE_BODY(where, how, within, OLD_DATA_SPACE, kUnknownOffsetFromStart)       \
  CASE_STATEMENT(where, how, within, OLD_POINTER_SPACE)                        \
  CASE_BODY(where, how, within, OLD_POINTER_SPACE, kUnknownOffsetFromStart)    \
  CASE_STATEMENT(where, how, within, CODE_SPACE)                               \
  CASE_BODY(where, how, within, CODE_SPACE, kUnknownOffsetFromStart)           \
  CASE_STATEMENT(where, how, within, CELL_SPACE)                               \
  CASE_BODY(where, how, within, CELL_SPACE, kUnknownOffsetFromStart)           \
  CASE_STATEMENT(where, how, within, MAP_SPACE)                                \
  CASE_BODY(where, how, within, MAP_SPACE, kUnknownOffsetFromStart)            \
  CASE_STATEMENT(where, how, within, kLargeData)                               \
  CASE_STATEMENT(where, how, within, kLargeCode)                               \
  CASE_STATEMENT(where, how, within, kLargeFixedArray)                         \
  CASE_BODY(where, how, within, kAnyOldSpace, kUnknownOffsetFromStart)

// This generates a case and a body for the new space (which has to do extra
// write barrier handling) and handles the other spaces with 8 fall-through
// cases and one body.
#define ALL_SPACES(where, how, within)                                         \
  CASE_STATEMENT(where, how, within, NEW_SPACE)                                \
  CASE_BODY(where, how, within, NEW_SPACE, kUnknownOffsetFromStart)            \
  CASE_STATEMENT(where, how, within, OLD_DATA_SPACE)                           \
  CASE_STATEMENT(where, how, within, OLD_POINTER_SPACE)                        \
  CASE_STATEMENT(where, how, within, CODE_SPACE)                               \
  CASE_STATEMENT(where, how, within, CELL_SPACE)                               \
  CASE_STATEMENT(where, how, within, MAP_SPACE)                                \
  CASE_STATEMENT(where, how, within, kLargeData)                               \
  CASE_STATEMENT(where, how, within, kLargeCode)                               \
  CASE_STATEMENT(where, how, within, kLargeFixedArray)                         \
  CASE_BODY(where, how, within, kAnyOldSpace, kUnknownOffsetFromStart)

857 858 859 860 861 862
#define ONE_PER_CODE_SPACE(where, how, within)                                 \
  CASE_STATEMENT(where, how, within, CODE_SPACE)                               \
  CASE_BODY(where, how, within, CODE_SPACE, kUnknownOffsetFromStart)           \
  CASE_STATEMENT(where, how, within, kLargeCode)                               \
  CASE_BODY(where, how, within, LO_SPACE, kUnknownOffsetFromStart)

863 864 865 866 867 868 869 870
#define EMIT_COMMON_REFERENCE_PATTERNS(pseudo_space_number,                    \
                                       space_number,                           \
                                       offset_from_start)                      \
  CASE_STATEMENT(kFromStart, kPlain, kStartOfObject, pseudo_space_number)      \
  CASE_BODY(kFromStart, kPlain, kStartOfObject, space_number, offset_from_start)

      // We generate 15 cases and bodies that process special tags that combine
      // the raw data tag and the length into one byte.
871
#define RAW_CASE(index, size)                                      \
872
      case kRawData + index: {                                     \
873 874 875 876 877 878 879
        byte* raw_data_out = reinterpret_cast<byte*>(current);     \
        source_->CopyRaw(raw_data_out, size);                      \
        current = reinterpret_cast<Object**>(raw_data_out + size); \
        break;                                                     \
      }
      COMMON_RAW_LENGTHS(RAW_CASE)
#undef RAW_CASE
880 881 882 883

      // Deserialize a chunk of raw data that doesn't have one of the popular
      // lengths.
      case kRawData: {
884 885
        int size = source_->GetInt();
        byte* raw_data_out = reinterpret_cast<byte*>(current);
886 887
        source_->CopyRaw(raw_data_out, size);
        current = reinterpret_cast<Object**>(raw_data_out + size);
888 889
        break;
      }
890 891 892 893

      // Deserialize a new object and write a pointer to it to the current
      // object.
      ONE_PER_SPACE(kNewObject, kPlain, kStartOfObject)
894 895
      // Support for direct instruction pointers in functions
      ONE_PER_CODE_SPACE(kNewObject, kPlain, kFirstInstruction)
896 897 898 899 900 901 902 903
      // Deserialize a new code object and write a pointer to its first
      // instruction to the current code object.
      ONE_PER_SPACE(kNewObject, kFromCode, kFirstInstruction)
      // Find a recently deserialized object using its offset from the current
      // allocation point and write a pointer to it to the current object.
      ALL_SPACES(kBackref, kPlain, kStartOfObject)
      // Find a recently deserialized code object using its offset from the
      // current allocation point and write a pointer to its first instruction
904 905
      // to the current code object or the instruction pointer in a function
      // object.
906
      ALL_SPACES(kBackref, kFromCode, kFirstInstruction)
907
      ALL_SPACES(kBackref, kPlain, kFirstInstruction)
908 909 910
      // Find an already deserialized object using its offset from the start
      // and write a pointer to it to the current object.
      ALL_SPACES(kFromStart, kPlain, kStartOfObject)
911
      ALL_SPACES(kFromStart, kPlain, kFirstInstruction)
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
      // Find an already deserialized code object using its offset from the
      // start and write a pointer to its first instruction to the current code
      // object.
      ALL_SPACES(kFromStart, kFromCode, kFirstInstruction)
      // Find an already deserialized object at one of the predetermined popular
      // offsets from the start and write a pointer to it in the current object.
      COMMON_REFERENCE_PATTERNS(EMIT_COMMON_REFERENCE_PATTERNS)
      // Find an object in the roots array and write a pointer to it to the
      // current object.
      CASE_STATEMENT(kRootArray, kPlain, kStartOfObject, 0)
      CASE_BODY(kRootArray, kPlain, kStartOfObject, 0, kUnknownOffsetFromStart)
      // Find an object in the partial snapshots cache and write a pointer to it
      // to the current object.
      CASE_STATEMENT(kPartialSnapshotCache, kPlain, kStartOfObject, 0)
      CASE_BODY(kPartialSnapshotCache,
                kPlain,
                kStartOfObject,
                0,
                kUnknownOffsetFromStart)
931 932 933 934 935 936 937 938
      // Find an code entry in the partial snapshots cache and
      // write a pointer to it to the current object.
      CASE_STATEMENT(kPartialSnapshotCache, kPlain, kFirstInstruction, 0)
      CASE_BODY(kPartialSnapshotCache,
                kPlain,
                kFirstInstruction,
                0,
                kUnknownOffsetFromStart)
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
      // Find an external reference and write a pointer to it to the current
      // object.
      CASE_STATEMENT(kExternalReference, kPlain, kStartOfObject, 0)
      CASE_BODY(kExternalReference,
                kPlain,
                kStartOfObject,
                0,
                kUnknownOffsetFromStart)
      // Find an external reference and write a pointer to it in the current
      // code object.
      CASE_STATEMENT(kExternalReference, kFromCode, kStartOfObject, 0)
      CASE_BODY(kExternalReference,
                kFromCode,
                kStartOfObject,
                0,
                kUnknownOffsetFromStart)

#undef CASE_STATEMENT
#undef CASE_BODY
#undef ONE_PER_SPACE
#undef ALL_SPACES
#undef EMIT_COMMON_REFERENCE_PATTERNS
#undef ASSIGN_DEST_SPACE

      case kNewPage: {
964 965
        int space = source_->Get();
        pages_[space].Add(last_object_address_);
966 967 968
        if (space == CODE_SPACE) {
          CPU::FlushICache(last_object_address_, Page::kPageSize);
        }
969 970
        break;
      }
971 972

      case kNativesStringResource: {
973 974 975 976 977 978 979
        int index = source_->Get();
        Vector<const char> source_vector = Natives::GetScriptSource(index);
        NativesExternalStringResource* resource =
            new NativesExternalStringResource(source_vector.start());
        *current++ = reinterpret_cast<Object*>(resource);
        break;
      }
980 981

      case kSynchronize: {
982 983 984 985
        // If we get here then that indicates that you have a mismatch between
        // the number of GC roots when serializing and deserializing.
        UNREACHABLE();
      }
986

987 988 989 990
      default:
        UNREACHABLE();
    }
  }
991
  ASSERT_EQ(current, limit);
992 993 994 995 996 997
}


void SnapshotByteSink::PutInt(uintptr_t integer, const char* description) {
  const int max_shift = ((kPointerSize * kBitsPerByte) / 7) * 7;
  for (int shift = max_shift; shift > 0; shift -= 7) {
998
    if (integer >= static_cast<uintptr_t>(1u) << shift) {
999
      Put((static_cast<int>((integer >> shift)) & 0x7f) | 0x80, "IntPart");
1000 1001
    }
  }
1002
  PutSection(static_cast<int>(integer & 0x7f), "IntLastPart");
1003 1004 1005 1006
}

#ifdef DEBUG

1007
void Deserializer::Synchronize(const char* tag) {
1008 1009 1010
  int data = source_->Get();
  // If this assert fails then that indicates that you have a mismatch between
  // the number of GC roots when serializing and deserializing.
1011
  ASSERT_EQ(kSynchronize, data);
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
  do {
    int character = source_->Get();
    if (character == 0) break;
    if (FLAG_debug_serialization) {
      PrintF("%c", character);
    }
  } while (true);
  if (FLAG_debug_serialization) {
    PrintF("\n");
  }
}


1025
void Serializer::Synchronize(const char* tag) {
1026
  sink_->Put(kSynchronize, tag);
1027 1028 1029
  int character;
  do {
    character = *tag++;
1030
    sink_->PutSection(character, "TagCharacter");
1031 1032 1033 1034 1035
  } while (character != 0);
}

#endif

1036
Serializer::Serializer(SnapshotByteSink* sink)
1037 1038
    : sink_(sink),
      current_root_index_(0),
1039
      external_reference_encoder_(new ExternalReferenceEncoder),
1040
      large_object_total_(0) {
1041 1042 1043 1044 1045 1046
  for (int i = 0; i <= LAST_SPACE; i++) {
    fullness_[i] = 0;
  }
}


1047 1048 1049 1050 1051
Serializer::~Serializer() {
  delete external_reference_encoder_;
}


1052
void StartupSerializer::SerializeStrongReferences() {
1053 1054 1055 1056 1057
  // No active threads.
  CHECK_EQ(NULL, ThreadState::FirstInUse());
  // No active or weak handles.
  CHECK(HandleScopeImplementer::instance()->blocks()->is_empty());
  CHECK_EQ(0, GlobalHandles::NumberOfWeakHandles());
1058 1059 1060 1061 1062 1063
  // We don't support serializing installed extensions.
  for (RegisteredExtension* ext = RegisteredExtension::first_extension();
       ext != NULL;
       ext = ext->next()) {
    CHECK_NE(v8::INSTALLED, ext->state());
  }
1064
  Heap::IterateStrongRoots(this, VISIT_ONLY_STRONG);
1065 1066 1067
}


1068
void PartialSerializer::Serialize(Object** object) {
1069
  this->VisitPointer(object);
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081

  // After we have done the partial serialization the partial snapshot cache
  // will contain some references needed to decode the partial snapshot.  We
  // fill it up with undefineds so it has a predictable length so the
  // deserialization code doesn't need to know the length.
  for (int index = partial_snapshot_cache_length_;
       index < kPartialSnapshotCacheCapacity;
       index++) {
    partial_snapshot_cache_[index] = Heap::undefined_value();
    startup_serializer_->VisitPointer(&partial_snapshot_cache_[index]);
  }
  partial_snapshot_cache_length_ = kPartialSnapshotCacheCapacity;
1082 1083 1084
}


1085
void Serializer::VisitPointers(Object** start, Object** end) {
1086
  for (Object** current = start; current < end; current++) {
1087
    if ((*current)->IsSmi()) {
1088
      sink_->Put(kRawData, "RawData");
1089 1090 1091 1092 1093
      sink_->PutInt(kPointerSize, "length");
      for (int i = 0; i < kPointerSize; i++) {
        sink_->Put(reinterpret_cast<byte*>(current)[i], "Byte");
      }
    } else {
1094
      SerializeObject(*current, kPlain, kStartOfObject);
1095
    }
1096 1097 1098 1099
  }
}


1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
Object* SerializerDeserializer::partial_snapshot_cache_[
    kPartialSnapshotCacheCapacity];
int SerializerDeserializer::partial_snapshot_cache_length_ = 0;


// This ensures that the partial snapshot cache keeps things alive during GC and
// tracks their movement.  When it is called during serialization of the startup
// snapshot the partial snapshot is empty, so nothing happens.  When the partial
// (context) snapshot is created, this array is populated with the pointers that
// the partial snapshot will need. As that happens we emit serialized objects to
// the startup snapshot that correspond to the elements of this cache array.  On
// deserialization we therefore need to visit the cache array.  This fills it up
// with pointers to deserialized objects.
1113
void SerializerDeserializer::Iterate(ObjectVisitor* visitor) {
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
  visitor->VisitPointers(
      &partial_snapshot_cache_[0],
      &partial_snapshot_cache_[partial_snapshot_cache_length_]);
}


// When deserializing we need to set the size of the snapshot cache.  This means
// the root iteration code (above) will iterate over array elements, writing the
// references to deserialized objects in them.
void SerializerDeserializer::SetSnapshotCacheSize(int size) {
  partial_snapshot_cache_length_ = size;
}


int PartialSerializer::PartialSnapshotCacheIndex(HeapObject* heap_object) {
  for (int i = 0; i < partial_snapshot_cache_length_; i++) {
    Object* entry = partial_snapshot_cache_[i];
    if (entry == heap_object) return i;
  }
1133

1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
  // We didn't find the object in the cache.  So we add it to the cache and
  // then visit the pointer so that it becomes part of the startup snapshot
  // and we can refer to it from the partial snapshot.
  int length = partial_snapshot_cache_length_;
  CHECK(length < kPartialSnapshotCacheCapacity);
  partial_snapshot_cache_[length] = heap_object;
  startup_serializer_->VisitPointer(&partial_snapshot_cache_[length]);
  // We don't recurse from the startup snapshot generator into the partial
  // snapshot generator.
  ASSERT(length == partial_snapshot_cache_length_);
  return partial_snapshot_cache_length_++;
}


int PartialSerializer::RootIndex(HeapObject* heap_object) {
1149 1150 1151 1152 1153 1154 1155 1156
  for (int i = 0; i < Heap::kRootListLength; i++) {
    Object* root = Heap::roots_address()[i];
    if (root == heap_object) return i;
  }
  return kInvalidRootIndex;
}


1157 1158 1159 1160 1161 1162 1163
// Encode the location of an already deserialized object in order to write its
// location into a later object.  We can encode the location as an offset from
// the start of the deserialized objects or as an offset backwards from the
// current allocation pointer.
void Serializer::SerializeReferenceToPreviousObject(
    int space,
    int address,
1164 1165
    HowToCode how_to_code,
    WhereToPoint where_to_point) {
1166 1167 1168 1169 1170 1171 1172 1173 1174
  int offset = CurrentAllocationAddress(space) - address;
  bool from_start = true;
  if (SpaceIsPaged(space)) {
    // For paged space it is simple to encode back from current allocation if
    // the object is on the same page as the current allocation pointer.
    if ((CurrentAllocationAddress(space) >> kPageSizeBits) ==
        (address >> kPageSizeBits)) {
      from_start = false;
      address = offset;
1175
    }
1176 1177 1178 1179 1180
  } else if (space == NEW_SPACE) {
    // For new space it is always simple to encode back from current allocation.
    if (offset < address) {
      from_start = false;
      address = offset;
1181
    }
1182 1183 1184 1185
  }
  // If we are actually dealing with real offsets (and not a numbering of
  // all objects) then we should shift out the bits that are always 0.
  if (!SpaceIsLarge(space)) address >>= kObjectAlignmentBits;
1186 1187 1188 1189 1190 1191 1192 1193
  if (from_start) {
#define COMMON_REFS_CASE(pseudo_space, actual_space, offset)                   \
    if (space == actual_space && address == offset &&                          \
        how_to_code == kPlain && where_to_point == kStartOfObject) {           \
      sink_->Put(kFromStart + how_to_code + where_to_point +                   \
                 pseudo_space, "RefSer");                                      \
    } else  /* NOLINT */
    COMMON_REFERENCE_PATTERNS(COMMON_REFS_CASE)
1194
#undef COMMON_REFS_CASE
1195 1196
    {  /* NOLINT */
      sink_->Put(kFromStart + how_to_code + where_to_point + space, "RefSer");
1197
      sink_->PutInt(address, "address");
1198
    }
1199 1200 1201
  } else {
    sink_->Put(kBackref + how_to_code + where_to_point + space, "BackRefSer");
    sink_->PutInt(address, "address");
1202 1203 1204 1205 1206 1207
  }
}


void StartupSerializer::SerializeObject(
    Object* o,
1208 1209
    HowToCode how_to_code,
    WhereToPoint where_to_point) {
1210 1211 1212 1213 1214 1215 1216 1217
  CHECK(o->IsHeapObject());
  HeapObject* heap_object = HeapObject::cast(o);

  if (address_mapper_.IsMapped(heap_object)) {
    int space = SpaceOfAlreadySerializedObject(heap_object);
    int address = address_mapper_.MappedTo(heap_object);
    SerializeReferenceToPreviousObject(space,
                                       address,
1218 1219
                                       how_to_code,
                                       where_to_point);
1220 1221 1222 1223 1224
  } else {
    // Object has not yet been serialized.  Serialize it here.
    ObjectSerializer object_serializer(this,
                                       heap_object,
                                       sink_,
1225 1226
                                       how_to_code,
                                       where_to_point);
1227 1228 1229 1230 1231 1232 1233 1234 1235
    object_serializer.Serialize();
  }
}


void StartupSerializer::SerializeWeakReferences() {
  for (int i = partial_snapshot_cache_length_;
       i < kPartialSnapshotCacheCapacity;
       i++) {
1236
    sink_->Put(kRootArray + kPlain + kStartOfObject, "RootSerialization");
1237 1238 1239 1240 1241 1242 1243 1244
    sink_->PutInt(Heap::kUndefinedValueRootIndex, "root_index");
  }
  Heap::IterateWeakRoots(this, VISIT_ALL);
}


void PartialSerializer::SerializeObject(
    Object* o,
1245 1246
    HowToCode how_to_code,
    WhereToPoint where_to_point) {
1247 1248 1249 1250 1251
  CHECK(o->IsHeapObject());
  HeapObject* heap_object = HeapObject::cast(o);

  int root_index;
  if ((root_index = RootIndex(heap_object)) != kInvalidRootIndex) {
1252
    sink_->Put(kRootArray + how_to_code + where_to_point, "RootSerialization");
1253 1254 1255 1256 1257 1258
    sink_->PutInt(root_index, "root_index");
    return;
  }

  if (ShouldBeInThePartialSnapshotCache(heap_object)) {
    int cache_index = PartialSnapshotCacheIndex(heap_object);
1259 1260
    sink_->Put(kPartialSnapshotCache + how_to_code + where_to_point,
               "PartialSnapshotCache");
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
    sink_->PutInt(cache_index, "partial_snapshot_cache_index");
    return;
  }

  // Pointers from the partial snapshot to the objects in the startup snapshot
  // should go through the root array or through the partial snapshot cache.
  // If this is not the case you may have to add something to the root array.
  ASSERT(!startup_serializer_->address_mapper()->IsMapped(heap_object));
  // All the symbols that the partial snapshot needs should be either in the
  // root table or in the partial snapshot cache.
  ASSERT(!heap_object->IsSymbol());

  if (address_mapper_.IsMapped(heap_object)) {
    int space = SpaceOfAlreadySerializedObject(heap_object);
    int address = address_mapper_.MappedTo(heap_object);
    SerializeReferenceToPreviousObject(space,
                                       address,
1278 1279
                                       how_to_code,
                                       where_to_point);
1280
  } else {
1281 1282 1283 1284
    // Object has not yet been serialized.  Serialize it here.
    ObjectSerializer serializer(this,
                                heap_object,
                                sink_,
1285 1286
                                how_to_code,
                                where_to_point);
1287
    serializer.Serialize();
1288 1289 1290 1291
  }
}


1292 1293
void Serializer::ObjectSerializer::Serialize() {
  int space = Serializer::SpaceOfObject(object_);
1294 1295
  int size = object_->Size();

1296 1297
  sink_->Put(kNewObject + reference_representation_ + space,
             "ObjectSerialization");
1298 1299
  sink_->PutInt(size >> kObjectAlignmentBits, "Size in words");

1300 1301
  LOG(SnapshotPositionEvent(object_->address(), sink_->Position()));

1302
  // Mark this object as already serialized.
1303
  bool start_new_page;
1304 1305
  int offset = serializer_->Allocate(space, size, &start_new_page);
  serializer_->address_mapper()->AddMapping(object_, offset);
1306
  if (start_new_page) {
1307
    sink_->Put(kNewPage, "NewPage");
1308 1309
    sink_->PutSection(space, "NewPageSpace");
  }
1310 1311

  // Serialize the map (first word of the object).
1312
  serializer_->SerializeObject(object_->map(), kPlain, kStartOfObject);
1313 1314

  // Serialize the rest of the object.
1315
  CHECK_EQ(0, bytes_processed_so_far_);
1316
  bytes_processed_so_far_ = kPointerSize;
1317
  object_->IterateBody(object_->map()->instance_type(), size, this);
1318 1319 1320 1321
  OutputRawData(object_->address() + size);
}


1322 1323
void Serializer::ObjectSerializer::VisitPointers(Object** start,
                                                 Object** end) {
1324 1325 1326
  Object** current = start;
  while (current < end) {
    while (current < end && (*current)->IsSmi()) current++;
1327
    if (current < end) OutputRawData(reinterpret_cast<Address>(current));
1328 1329

    while (current < end && !(*current)->IsSmi()) {
1330
      serializer_->SerializeObject(*current, kPlain, kStartOfObject);
1331 1332 1333
      bytes_processed_so_far_ += kPointerSize;
      current++;
    }
1334 1335 1336 1337
  }
}


1338 1339
void Serializer::ObjectSerializer::VisitExternalReferences(Address* start,
                                                           Address* end) {
1340 1341 1342 1343
  Address references_start = reinterpret_cast<Address>(start);
  OutputRawData(references_start);

  for (Address* current = start; current < end; current++) {
1344
    sink_->Put(kExternalReference + kPlain + kStartOfObject, "ExternalRef");
1345 1346 1347
    int reference_id = serializer_->EncodeExternalReference(*current);
    sink_->PutInt(reference_id, "reference id");
  }
1348
  bytes_processed_so_far_ += static_cast<int>((end - start) * kPointerSize);
1349 1350 1351
}


1352
void Serializer::ObjectSerializer::VisitRuntimeEntry(RelocInfo* rinfo) {
1353 1354 1355 1356 1357
  Address target_start = rinfo->target_address_address();
  OutputRawData(target_start);
  Address target = rinfo->target_address();
  uint32_t encoding = serializer_->EncodeExternalReference(target);
  CHECK(target == NULL ? encoding == 0 : encoding != 0);
1358 1359 1360 1361 1362 1363 1364 1365
  int representation;
  // Can't use a ternary operator because of gcc.
  if (rinfo->IsCodedSpecially()) {
    representation = kStartOfObject + kFromCode;
  } else {
    representation = kStartOfObject + kPlain;
  }
  sink_->Put(kExternalReference + representation, "ExternalReference");
1366
  sink_->PutInt(encoding, "reference id");
1367
  bytes_processed_so_far_ += rinfo->target_address_size();
1368 1369 1370
}


1371 1372
void Serializer::ObjectSerializer::VisitCodeTarget(RelocInfo* rinfo) {
  CHECK(RelocInfo::IsCodeTarget(rinfo->rmode()));
1373 1374 1375
  Address target_start = rinfo->target_address_address();
  OutputRawData(target_start);
  Code* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
1376
  serializer_->SerializeObject(target, kFromCode, kFirstInstruction);
1377
  bytes_processed_so_far_ += rinfo->target_address_size();
1378 1379 1380
}


1381 1382 1383 1384 1385 1386 1387 1388
void Serializer::ObjectSerializer::VisitCodeEntry(Address entry_address) {
  Code* target = Code::cast(Code::GetObjectFromEntryAddress(entry_address));
  OutputRawData(entry_address);
  serializer_->SerializeObject(target, kPlain, kFirstInstruction);
  bytes_processed_so_far_ += kPointerSize;
}


1389 1390 1391 1392 1393 1394 1395
void Serializer::ObjectSerializer::VisitGlobalPropertyCell(RelocInfo* rinfo) {
  // We shouldn't have any global property cell references in code
  // objects in the snapshot.
  UNREACHABLE();
}


1396
void Serializer::ObjectSerializer::VisitExternalAsciiString(
1397 1398 1399 1400
    v8::String::ExternalAsciiStringResource** resource_pointer) {
  Address references_start = reinterpret_cast<Address>(resource_pointer);
  OutputRawData(references_start);
  for (int i = 0; i < Natives::GetBuiltinsCount(); i++) {
1401
    Object* source = Heap::natives_source_cache()->get(i);
1402
    if (!source->IsUndefined()) {
1403
      ExternalAsciiString* string = ExternalAsciiString::cast(source);
1404 1405 1406
      typedef v8::String::ExternalAsciiStringResource Resource;
      Resource* resource = string->resource();
      if (resource == *resource_pointer) {
1407
        sink_->Put(kNativesStringResource, "NativesStringResource");
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
        sink_->PutSection(i, "NativesStringResourceEnd");
        bytes_processed_so_far_ += sizeof(resource);
        return;
      }
    }
  }
  // One of the strings in the natives cache should match the resource.  We
  // can't serialize any other kinds of external strings.
  UNREACHABLE();
}


1420
void Serializer::ObjectSerializer::OutputRawData(Address up_to) {
1421
  Address object_start = object_->address();
1422
  int up_to_offset = static_cast<int>(up_to - object_start);
1423
  int skipped = up_to_offset - bytes_processed_so_far_;
1424 1425
  // This assert will fail if the reloc info gives us the target_address_address
  // locations in a non-ascending order.  Luckily that doesn't happen.
1426 1427
  ASSERT(skipped >= 0);
  if (skipped != 0) {
1428 1429 1430
    Address base = object_start + bytes_processed_so_far_;
#define RAW_CASE(index, length)                                                \
    if (skipped == length) {                                                   \
1431
      sink_->PutSection(kRawData + index, "RawDataFixed");                     \
1432 1433 1434 1435
    } else  /* NOLINT */
    COMMON_RAW_LENGTHS(RAW_CASE)
#undef RAW_CASE
    {  /* NOLINT */
1436
      sink_->Put(kRawData, "RawData");
1437 1438
      sink_->PutInt(skipped, "length");
    }
1439
    for (int i = 0; i < skipped; i++) {
1440 1441
      unsigned int data = base[i];
      sink_->PutSection(data, "Byte");
1442
    }
1443
    bytes_processed_so_far_ += skipped;
1444 1445 1446 1447
  }
}


1448
int Serializer::SpaceOfObject(HeapObject* object) {
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
  for (int i = FIRST_SPACE; i <= LAST_SPACE; i++) {
    AllocationSpace s = static_cast<AllocationSpace>(i);
    if (Heap::InSpace(object, s)) {
      if (i == LO_SPACE) {
        if (object->IsCode()) {
          return kLargeCode;
        } else if (object->IsFixedArray()) {
          return kLargeFixedArray;
        } else {
          return kLargeData;
        }
      }
      return i;
    }
  }
  UNREACHABLE();
  return 0;
}


1469
int Serializer::SpaceOfAlreadySerializedObject(HeapObject* object) {
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
  for (int i = FIRST_SPACE; i <= LAST_SPACE; i++) {
    AllocationSpace s = static_cast<AllocationSpace>(i);
    if (Heap::InSpace(object, s)) {
      return i;
    }
  }
  UNREACHABLE();
  return 0;
}


1481 1482
int Serializer::Allocate(int space, int size, bool* new_page) {
  CHECK(space >= 0 && space < kNumberOfSpaces);
1483 1484 1485
  if (SpaceIsLarge(space)) {
    // In large object space we merely number the objects instead of trying to
    // determine some sort of address.
1486
    *new_page = true;
1487
    large_object_total_ += size;
1488 1489
    return fullness_[LO_SPACE]++;
  }
1490 1491 1492 1493
  *new_page = false;
  if (fullness_[space] == 0) {
    *new_page = true;
  }
1494 1495 1496 1497 1498 1499 1500
  if (SpaceIsPaged(space)) {
    // Paged spaces are a little special.  We encode their addresses as if the
    // pages were all contiguous and each page were filled up in the range
    // 0 - Page::kObjectAreaSize.  In practice the pages may not be contiguous
    // and allocation does not start at offset 0 in the page, but this scheme
    // means the deserializer can get the page number quickly by shifting the
    // serialized address.
1501
    CHECK(IsPowerOf2(Page::kPageSize));
1502
    int used_in_this_page = (fullness_[space] & (Page::kPageSize - 1));
1503
    CHECK(size <= Page::kObjectAreaSize);
1504
    if (used_in_this_page + size > Page::kObjectAreaSize) {
1505
      *new_page = true;
1506 1507 1508 1509 1510 1511 1512 1513 1514
      fullness_[space] = RoundUp(fullness_[space], Page::kPageSize);
    }
  }
  int allocation_address = fullness_[space];
  fullness_[space] = allocation_address + size;
  return allocation_address;
}


1515
} }  // namespace v8::internal