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

5 6 7 8
#include "src/v8.h"

#include "src/accessors.h"
#include "src/api.h"
9
#include "src/base/platform/platform.h"
10
#include "src/bootstrapper.h"
11
#include "src/code-stubs.h"
12
#include "src/cpu-profiler.h"
13 14 15
#include "src/deoptimizer.h"
#include "src/execution.h"
#include "src/global-handles.h"
16 17
#include "src/ic/ic.h"
#include "src/ic/stub-cache.h"
18
#include "src/objects.h"
19
#include "src/parser.h"
20
#include "src/runtime/runtime.h"
21 22 23 24
#include "src/snapshot/natives.h"
#include "src/snapshot/serialize.h"
#include "src/snapshot/snapshot.h"
#include "src/snapshot/snapshot-source-sink.h"
25
#include "src/v8threads.h"
26
#include "src/version.h"
27

28 29
namespace v8 {
namespace internal {
30

31

32 33 34 35
// -----------------------------------------------------------------------------
// Coding of external references.


36 37 38 39 40 41
ExternalReferenceTable* ExternalReferenceTable::instance(Isolate* isolate) {
  ExternalReferenceTable* external_reference_table =
      isolate->external_reference_table();
  if (external_reference_table == NULL) {
    external_reference_table = new ExternalReferenceTable(isolate);
    isolate->set_external_reference_table(external_reference_table);
42
  }
43 44
  return external_reference_table;
}
45 46


47
ExternalReferenceTable::ExternalReferenceTable(Isolate* isolate) {
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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  // Miscellaneous
  Add(ExternalReference::roots_array_start(isolate).address(),
      "Heap::roots_array_start()");
  Add(ExternalReference::address_of_stack_limit(isolate).address(),
      "StackGuard::address_of_jslimit()");
  Add(ExternalReference::address_of_real_stack_limit(isolate).address(),
      "StackGuard::address_of_real_jslimit()");
  Add(ExternalReference::new_space_start(isolate).address(),
      "Heap::NewSpaceStart()");
  Add(ExternalReference::new_space_mask(isolate).address(),
      "Heap::NewSpaceMask()");
  Add(ExternalReference::new_space_allocation_limit_address(isolate).address(),
      "Heap::NewSpaceAllocationLimitAddress()");
  Add(ExternalReference::new_space_allocation_top_address(isolate).address(),
      "Heap::NewSpaceAllocationTopAddress()");
  Add(ExternalReference::debug_step_in_fp_address(isolate).address(),
      "Debug::step_in_fp_addr()");
  Add(ExternalReference::mod_two_doubles_operation(isolate).address(),
      "mod_two_doubles");
  // Keyed lookup cache.
  Add(ExternalReference::keyed_lookup_cache_keys(isolate).address(),
      "KeyedLookupCache::keys()");
  Add(ExternalReference::keyed_lookup_cache_field_offsets(isolate).address(),
      "KeyedLookupCache::field_offsets()");
  Add(ExternalReference::handle_scope_next_address(isolate).address(),
      "HandleScope::next");
  Add(ExternalReference::handle_scope_limit_address(isolate).address(),
      "HandleScope::limit");
  Add(ExternalReference::handle_scope_level_address(isolate).address(),
      "HandleScope::level");
  Add(ExternalReference::new_deoptimizer_function(isolate).address(),
      "Deoptimizer::New()");
  Add(ExternalReference::compute_output_frames_function(isolate).address(),
      "Deoptimizer::ComputeOutputFrames()");
  Add(ExternalReference::address_of_min_int().address(),
      "LDoubleConstant::min_int");
  Add(ExternalReference::address_of_one_half().address(),
      "LDoubleConstant::one_half");
  Add(ExternalReference::isolate_address(isolate).address(), "isolate");
  Add(ExternalReference::address_of_negative_infinity().address(),
      "LDoubleConstant::negative_infinity");
  Add(ExternalReference::power_double_double_function(isolate).address(),
      "power_double_double_function");
  Add(ExternalReference::power_double_int_function(isolate).address(),
      "power_double_int_function");
  Add(ExternalReference::math_log_double_function(isolate).address(),
      "std::log");
  Add(ExternalReference::store_buffer_top(isolate).address(),
      "store_buffer_top");
  Add(ExternalReference::address_of_the_hole_nan().address(), "the_hole_nan");
  Add(ExternalReference::get_date_field_function(isolate).address(),
      "JSDate::GetField");
  Add(ExternalReference::date_cache_stamp(isolate).address(),
      "date_cache_stamp");
  Add(ExternalReference::address_of_pending_message_obj(isolate).address(),
      "address_of_pending_message_obj");
  Add(ExternalReference::get_make_code_young_function(isolate).address(),
      "Code::MakeCodeYoung");
  Add(ExternalReference::cpu_features().address(), "cpu_features");
107 108 109 110
  Add(ExternalReference::old_space_allocation_top_address(isolate).address(),
      "Heap::OldSpaceAllocationTopAddress");
  Add(ExternalReference::old_space_allocation_limit_address(isolate).address(),
      "Heap::OldSpaceAllocationLimitAddress");
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
  Add(ExternalReference::allocation_sites_list_address(isolate).address(),
      "Heap::allocation_sites_list_address()");
  Add(ExternalReference::address_of_uint32_bias().address(), "uint32_bias");
  Add(ExternalReference::get_mark_code_as_executed_function(isolate).address(),
      "Code::MarkCodeAsExecuted");
  Add(ExternalReference::is_profiling_address(isolate).address(),
      "CpuProfiler::is_profiling");
  Add(ExternalReference::scheduled_exception_address(isolate).address(),
      "Isolate::scheduled_exception");
  Add(ExternalReference::invoke_function_callback(isolate).address(),
      "InvokeFunctionCallback");
  Add(ExternalReference::invoke_accessor_getter_callback(isolate).address(),
      "InvokeAccessorGetterCallback");
  Add(ExternalReference::flush_icache_function(isolate).address(),
      "CpuFeatures::FlushICache");
  Add(ExternalReference::log_enter_external_function(isolate).address(),
      "Logger::EnterExternal");
  Add(ExternalReference::log_leave_external_function(isolate).address(),
      "Logger::LeaveExternal");
  Add(ExternalReference::address_of_minus_one_half().address(),
      "double_constants.minus_one_half");
  Add(ExternalReference::stress_deopt_count(isolate).address(),
      "Isolate::stress_deopt_count_address()");

  // Debug addresses
  Add(ExternalReference::debug_after_break_target_address(isolate).address(),
      "Debug::after_break_target_address()");
  Add(ExternalReference::debug_restarter_frame_function_pointer_address(isolate)
          .address(),
      "Debug::restarter_frame_function_pointer_address()");
  Add(ExternalReference::debug_is_active_address(isolate).address(),
      "Debug::is_active_address()");

#ifndef V8_INTERPRETED_REGEXP
  Add(ExternalReference::re_case_insensitive_compare_uc16(isolate).address(),
      "NativeRegExpMacroAssembler::CaseInsensitiveCompareUC16()");
  Add(ExternalReference::re_check_stack_guard_state(isolate).address(),
      "RegExpMacroAssembler*::CheckStackGuardState()");
  Add(ExternalReference::re_grow_stack(isolate).address(),
      "NativeRegExpMacroAssembler::GrowStack()");
  Add(ExternalReference::re_word_character_map().address(),
      "NativeRegExpMacroAssembler::word_character_map");
  Add(ExternalReference::address_of_regexp_stack_limit(isolate).address(),
      "RegExpStack::limit_address()");
  Add(ExternalReference::address_of_regexp_stack_memory_address(isolate)
          .address(),
      "RegExpStack::memory_address()");
  Add(ExternalReference::address_of_regexp_stack_memory_size(isolate).address(),
      "RegExpStack::memory_size()");
  Add(ExternalReference::address_of_static_offsets_vector(isolate).address(),
      "OffsetsVector::static_offsets_vector");
#endif  // V8_INTERPRETED_REGEXP

164 165 166 167 168 169 170 171 172 173 174 175
  // 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 {
    uint16_t id;
    const char* name;
  };
176

177 178 179 180 181
  static const RefTableEntry c_builtins[] = {
#define DEF_ENTRY_C(name, ignored)           \
  { Builtins::c_##name, "Builtins::" #name } \
  ,
      BUILTIN_LIST_C(DEF_ENTRY_C)
182
#undef DEF_ENTRY_C
183
  };
184

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
  for (unsigned i = 0; i < arraysize(c_builtins); ++i) {
    ExternalReference ref(static_cast<Builtins::CFunctionId>(c_builtins[i].id),
                          isolate);
    Add(ref.address(), c_builtins[i].name);
  }

  static const RefTableEntry builtins[] = {
#define DEF_ENTRY_C(name, ignored)          \
  { Builtins::k##name, "Builtins::" #name } \
  ,
#define DEF_ENTRY_A(name, i1, i2, i3)       \
  { Builtins::k##name, "Builtins::" #name } \
  ,
      BUILTIN_LIST_C(DEF_ENTRY_C) BUILTIN_LIST_A(DEF_ENTRY_A)
          BUILTIN_LIST_DEBUG_A(DEF_ENTRY_A)
200 201
#undef DEF_ENTRY_C
#undef DEF_ENTRY_A
202
  };
203

204 205 206 207
  for (unsigned i = 0; i < arraysize(builtins); ++i) {
    ExternalReference ref(static_cast<Builtins::Name>(builtins[i].id), isolate);
    Add(ref.address(), builtins[i].name);
  }
208

209 210 211 212
  static const RefTableEntry runtime_functions[] = {
#define RUNTIME_ENTRY(name, i1, i2)       \
  { Runtime::k##name, "Runtime::" #name } \
  ,
213
      FOR_EACH_INTRINSIC(RUNTIME_ENTRY)
214
#undef RUNTIME_ENTRY
215
  };
216

217 218 219 220 221
  for (unsigned i = 0; i < arraysize(runtime_functions); ++i) {
    ExternalReference ref(
        static_cast<Runtime::FunctionId>(runtime_functions[i].id), isolate);
    Add(ref.address(), runtime_functions[i].name);
  }
222 223

  // Stat counters
224
  struct StatsRefTableEntry {
225
    StatsCounter* (Counters::*counter)();
226 227 228
    const char* name;
  };

229 230 231 232 233
  static const StatsRefTableEntry stats_ref_table[] = {
#define COUNTER_ENTRY(name, caption)      \
  { &Counters::name, "Counters::" #name } \
  ,
      STATS_COUNTER_LIST_1(COUNTER_ENTRY) STATS_COUNTER_LIST_2(COUNTER_ENTRY)
234
#undef COUNTER_ENTRY
235
  };
236

237
  Counters* counters = isolate->counters();
238 239 240 241 242 243 244 245 246
  for (unsigned i = 0; i < arraysize(stats_ref_table); ++i) {
    // To make sure the indices are not dependent on whether counters are
    // enabled, use a dummy address as filler.
    Address address = NotAvailable();
    StatsCounter* counter = (counters->*(stats_ref_table[i].counter))();
    if (counter->Enabled()) {
      address = reinterpret_cast<Address>(counter->GetInternalPointer());
    }
    Add(address, stats_ref_table[i].name);
247
  }
248 249

  // Top addresses
250 251 252
  static const char* address_names[] = {
#define BUILD_NAME_LITERAL(Name, name) "Isolate::" #name "_address",
      FOR_EACH_ISOLATE_ADDRESS_NAME(BUILD_NAME_LITERAL) NULL
253
#undef BUILD_NAME_LITERAL
254 255
  };

256 257 258
  for (int i = 0; i < Isolate::kIsolateAddressCount; ++i) {
    Add(isolate->get_address_from_id(static_cast<Isolate::AddressId>(i)),
        address_names[i]);
259 260 261
  }

  // Accessors
262 263 264 265 266 267 268 269 270 271
  struct AccessorRefTable {
    Address address;
    const char* name;
  };

  static const AccessorRefTable accessors[] = {
#define ACCESSOR_INFO_DECLARATION(name)                                     \
  { FUNCTION_ADDR(&Accessors::name##Getter), "Accessors::" #name "Getter" } \
  , {FUNCTION_ADDR(&Accessors::name##Setter), "Accessors::" #name "Setter"},
      ACCESSOR_INFO_LIST(ACCESSOR_INFO_DECLARATION)
272
#undef ACCESSOR_INFO_DECLARATION
273 274 275 276 277
  };

  for (unsigned i = 0; i < arraysize(accessors); ++i) {
    Add(accessors[i].address, accessors[i].name);
  }
278

279 280
  StubCache* stub_cache = isolate->stub_cache();

281
  // Stub cache tables
282
  Add(stub_cache->key_reference(StubCache::kPrimary).address(),
283
      "StubCache::primary_->key");
284
  Add(stub_cache->value_reference(StubCache::kPrimary).address(),
285
      "StubCache::primary_->value");
286
  Add(stub_cache->map_reference(StubCache::kPrimary).address(),
287
      "StubCache::primary_->map");
288
  Add(stub_cache->key_reference(StubCache::kSecondary).address(),
289
      "StubCache::secondary_->key");
290
  Add(stub_cache->value_reference(StubCache::kSecondary).address(),
291
      "StubCache::secondary_->value");
292
  Add(stub_cache->map_reference(StubCache::kSecondary).address(),
293
      "StubCache::secondary_->map");
294 295

  // Runtime entries
296
  Add(ExternalReference::delete_handle_scope_extensions(isolate).address(),
297
      "HandleScope::DeleteExtensions");
298 299
  Add(ExternalReference::incremental_marking_record_write_function(isolate)
          .address(),
300
      "IncrementalMarking::RecordWrite");
301
  Add(ExternalReference::store_buffer_overflow_function(isolate).address(),
302
      "StoreBuffer::StoreBufferOverflow");
303

304 305
  // Add a small set of deopt entry addresses to encoder without generating the
  // deopt table code, which isn't possible at deserialization time.
306
  HandleScope scope(isolate);
307 308
  for (int entry = 0; entry < kDeoptTableSerializeEntryCount; ++entry) {
    Address address = Deoptimizer::GetDeoptimizationEntry(
309
        isolate,
310 311 312
        entry,
        Deoptimizer::LAZY,
        Deoptimizer::CALCULATE_ENTRY_ADDRESS);
313
    Add(address, "lazy_deopt");
314
  }
315 316 317
}


318 319 320 321
ExternalReferenceEncoder::ExternalReferenceEncoder(Isolate* isolate) {
  map_ = isolate->external_reference_map();
  if (map_ != NULL) return;
  map_ = new HashMap(HashMap::PointersMatch);
322 323 324 325 326
  ExternalReferenceTable* table = ExternalReferenceTable::instance(isolate);
  for (int i = 0; i < table->size(); ++i) {
    Address addr = table->address(i);
    if (addr == ExternalReferenceTable::NotAvailable()) continue;
    // We expect no duplicate external references entries in the table.
327 328
    DCHECK_NULL(map_->Lookup(addr, Hash(addr)));
    map_->LookupOrInsert(addr, Hash(addr))->value = reinterpret_cast<void*>(i);
329
  }
330
  isolate->set_external_reference_map(map_);
331 332 333
}


334 335
uint32_t ExternalReferenceEncoder::Encode(Address address) const {
  DCHECK_NOT_NULL(address);
336
  HashMap::Entry* entry =
337
      const_cast<HashMap*>(map_)->Lookup(address, Hash(address));
338 339
  DCHECK_NOT_NULL(entry);
  return static_cast<uint32_t>(reinterpret_cast<intptr_t>(entry->value));
340 341 342
}


343 344 345
const char* ExternalReferenceEncoder::NameOfAddress(Isolate* isolate,
                                                    Address address) const {
  HashMap::Entry* entry =
346
      const_cast<HashMap*>(map_)->Lookup(address, Hash(address));
347 348 349
  if (entry == NULL) return "<unknown>";
  uint32_t i = static_cast<uint32_t>(reinterpret_cast<intptr_t>(entry->value));
  return ExternalReferenceTable::instance(isolate)->name(i);
350 351 352
}


353 354 355 356
RootIndexMap::RootIndexMap(Isolate* isolate) {
  map_ = isolate->root_index_map();
  if (map_ != NULL) return;
  map_ = new HashMap(HashMap::PointersMatch);
357
  Object** root_array = isolate->heap()->roots_array_start();
358
  for (uint32_t i = 0; i < Heap::kStrongRootListLength; i++) {
359 360 361 362 363 364
    Heap::RootListIndex root_index = static_cast<Heap::RootListIndex>(i);
    Object* root = root_array[root_index];
    // Omit root entries that can be written after initialization. They must
    // not be referenced through the root list in the snapshot.
    if (root->IsHeapObject() &&
        isolate->heap()->RootCanBeTreatedAsConstant(root_index)) {
365
      HeapObject* heap_object = HeapObject::cast(root);
366
      HashMap::Entry* entry = LookupEntry(map_, heap_object, false);
367 368 369
      if (entry != NULL) {
        // Some are initialized to a previous value in the root list.
        DCHECK_LT(GetValue(entry), i);
370
      } else {
371
        SetValue(LookupEntry(map_, heap_object, true), i);
372 373 374
      }
    }
  }
375
  isolate->set_root_index_map(map_);
376 377 378
}


379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
class CodeAddressMap: public CodeEventLogger {
 public:
  explicit CodeAddressMap(Isolate* isolate)
      : isolate_(isolate) {
    isolate->logger()->addCodeEventListener(this);
  }

  virtual ~CodeAddressMap() {
    isolate_->logger()->removeCodeEventListener(this);
  }

  virtual void CodeMoveEvent(Address from, Address to) {
    address_to_name_map_.Move(from, to);
  }

394 395 396
  virtual void CodeDisableOptEvent(Code* code, SharedFunctionInfo* shared) {
  }

397 398 399 400 401 402 403 404 405 406 407
  virtual void CodeDeleteEvent(Address from) {
    address_to_name_map_.Remove(from);
  }

  const char* Lookup(Address address) {
    return address_to_name_map_.Lookup(address);
  }

 private:
  class NameMap {
   public:
408
    NameMap() : impl_(HashMap::PointersMatch) {}
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438

    ~NameMap() {
      for (HashMap::Entry* p = impl_.Start(); p != NULL; p = impl_.Next(p)) {
        DeleteArray(static_cast<const char*>(p->value));
      }
    }

    void Insert(Address code_address, const char* name, int name_size) {
      HashMap::Entry* entry = FindOrCreateEntry(code_address);
      if (entry->value == NULL) {
        entry->value = CopyName(name, name_size);
      }
    }

    const char* Lookup(Address code_address) {
      HashMap::Entry* entry = FindEntry(code_address);
      return (entry != NULL) ? static_cast<const char*>(entry->value) : NULL;
    }

    void Remove(Address code_address) {
      HashMap::Entry* entry = FindEntry(code_address);
      if (entry != NULL) {
        DeleteArray(static_cast<char*>(entry->value));
        RemoveEntry(entry);
      }
    }

    void Move(Address from, Address to) {
      if (from == to) return;
      HashMap::Entry* from_entry = FindEntry(from);
439
      DCHECK(from_entry != NULL);
440 441 442
      void* value = from_entry->value;
      RemoveEntry(from_entry);
      HashMap::Entry* to_entry = FindOrCreateEntry(to);
443
      DCHECK(to_entry->value == NULL);
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
      to_entry->value = value;
    }

   private:
    static char* CopyName(const char* name, int name_size) {
      char* result = NewArray<char>(name_size + 1);
      for (int i = 0; i < name_size; ++i) {
        char c = name[i];
        if (c == '\0') c = ' ';
        result[i] = c;
      }
      result[name_size] = '\0';
      return result;
    }

    HashMap::Entry* FindOrCreateEntry(Address code_address) {
460 461
      return impl_.LookupOrInsert(code_address,
                                  ComputePointerHash(code_address));
462 463 464
    }

    HashMap::Entry* FindEntry(Address code_address) {
465
      return impl_.Lookup(code_address, ComputePointerHash(code_address));
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    }

    void RemoveEntry(HashMap::Entry* entry) {
      impl_.Remove(entry->key, entry->hash);
    }

    HashMap impl_;

    DISALLOW_COPY_AND_ASSIGN(NameMap);
  };

  virtual void LogRecordedBuffer(Code* code,
                                 SharedFunctionInfo*,
                                 const char* name,
                                 int length) {
    address_to_name_map_.Insert(code->address(), name, length);
  }

  NameMap address_to_name_map_;
  Isolate* isolate_;
};


489 490 491 492 493
void Deserializer::DecodeReservation(
    Vector<const SerializedData::Reservation> res) {
  DCHECK_EQ(0, reservations_[NEW_SPACE].length());
  STATIC_ASSERT(NEW_SPACE == 0);
  int current_space = NEW_SPACE;
494
  for (auto& r : res) {
495 496 497 498
    reservations_[current_space].Add({r.chunk_size(), NULL, NULL});
    if (r.is_last()) current_space++;
  }
  DCHECK_EQ(kNumberOfSpaces, current_space);
499
  for (int i = 0; i < kNumberOfPreallocatedSpaces; i++) current_chunk_[i] = 0;
500 501 502
}


503
void Deserializer::FlushICacheForNewCodeObjects() {
504 505 506 507 508 509 510 511 512 513 514 515
  if (!deserializing_user_code_) {
    // The entire isolate is newly deserialized. Simply flush all code pages.
    PageIterator it(isolate_->heap()->code_space());
    while (it.has_next()) {
      Page* p = it.next();
      CpuFeatures::FlushICache(p->area_start(),
                               p->area_end() - p->area_start());
    }
  }
  for (Code* code : new_code_objects_) {
    CpuFeatures::FlushICache(code->instruction_start(),
                             code->instruction_size());
516 517 518 519
  }
}


520
bool Deserializer::ReserveSpace() {
521 522 523 524 525
#ifdef DEBUG
  for (int i = NEW_SPACE; i < kNumberOfSpaces; ++i) {
    CHECK(reservations_[i].length() > 0);
  }
#endif  // DEBUG
526 527 528 529 530 531 532 533
  if (!isolate_->heap()->ReserveSpace(reservations_)) return false;
  for (int i = 0; i < kNumberOfPreallocatedSpaces; i++) {
    high_water_[i] = reservations_[i][0].start;
  }
  return true;
}


534
void Deserializer::Initialize(Isolate* isolate) {
535 536
  DCHECK_NULL(isolate_);
  DCHECK_NOT_NULL(isolate);
537
  isolate_ = isolate;
538 539 540 541
  DCHECK_NULL(external_reference_table_);
  external_reference_table_ = ExternalReferenceTable::instance(isolate);
  CHECK_EQ(magic_number_,
           SerializedData::ComputeMagicNumber(external_reference_table_));
542 543 544 545 546
}


void Deserializer::Deserialize(Isolate* isolate) {
  Initialize(isolate);
547
  if (!ReserveSpace()) V8::FatalProcessOutOfMemory("deserializing context");
548
  // No active threads.
549
  DCHECK_NULL(isolate_->thread_manager()->FirstThreadStateInUse());
550
  // No active handles.
551
  DCHECK(isolate_->handle_scope_implementer()->blocks()->is_empty());
552 553 554 555 556 557 558 559 560

  {
    DisallowHeapAllocation no_gc;
    isolate_->heap()->IterateSmiRoots(this);
    isolate_->heap()->IterateStrongRoots(this, VISIT_ONLY_STRONG);
    isolate_->heap()->RepairFreeListsAfterDeserialization();
    isolate_->heap()->IterateWeakRoots(this, VISIT_ALL);
    DeserializeDeferredObjects();
  }
561 562

  isolate_->heap()->set_native_contexts_list(
563
      isolate_->heap()->code_stub_context());
564

565 566 567 568 569 570 571
  // The allocation site list is build during root iteration, but if no sites
  // were encountered then it needs to be initialized to undefined.
  if (isolate_->heap()->allocation_sites_list() == Smi::FromInt(0)) {
    isolate_->heap()->set_allocation_sites_list(
        isolate_->heap()->undefined_value());
  }

572 573 574 575
  // Update data pointers to the external strings containing natives sources.
  for (int i = 0; i < Natives::GetBuiltinsCount(); i++) {
    Object* source = isolate_->heap()->natives_source_cache()->get(i);
    if (!source->IsUndefined()) {
576
      ExternalOneByteString::cast(source)->update_data_cache();
577 578
    }
  }
579

580 581 582 583 584 585 586
  for (int i = 0; i < CodeStubNatives::GetBuiltinsCount(); i++) {
    Object* source = isolate_->heap()->code_stub_natives_source_cache()->get(i);
    if (!source->IsUndefined()) {
      ExternalOneByteString::cast(source)->update_data_cache();
    }
  }

587 588
  FlushICacheForNewCodeObjects();

589 590 591
  // Issue code events for newly deserialized code objects.
  LOG_CODE_EVENT(isolate_, LogCodeObjects());
  LOG_CODE_EVENT(isolate_, LogCompiledFunctions());
592 593 594
}


595
MaybeHandle<Object> Deserializer::DeserializePartial(
596 597
    Isolate* isolate, Handle<JSGlobalProxy> global_proxy,
    Handle<FixedArray>* outdated_contexts_out) {
598
  Initialize(isolate);
599
  if (!ReserveSpace()) {
600
    V8::FatalProcessOutOfMemory("deserialize context");
601
    return MaybeHandle<Object>();
602
  }
603

604 605 606 607
  Vector<Handle<Object> > attached_objects = Vector<Handle<Object> >::New(1);
  attached_objects[kGlobalProxyReference] = global_proxy;
  SetAttachedObjects(attached_objects);

608
  DisallowHeapAllocation no_gc;
609 610 611 612
  // Keep track of the code space start and end pointers in case new
  // code objects were unserialized
  OldSpace* code_space = isolate_->heap()->code_space();
  Address start_address = code_space->top();
613 614 615
  Object* root;
  Object* outdated_contexts;
  VisitPointer(&root);
616
  DeserializeDeferredObjects();
617
  VisitPointer(&outdated_contexts);
618

619 620 621
  // There's no code deserialized here. If this assert fires then that's
  // changed and logging should be added to notify the profiler et al of the
  // new code, which also has to be flushed from instruction cache.
622
  CHECK_EQ(start_address, code_space->top());
623 624 625 626 627 628 629 630 631 632 633 634 635
  CHECK(outdated_contexts->IsFixedArray());
  *outdated_contexts_out =
      Handle<FixedArray>(FixedArray::cast(outdated_contexts), isolate);
  return Handle<Object>(root, isolate);
}


MaybeHandle<SharedFunctionInfo> Deserializer::DeserializeCode(
    Isolate* isolate) {
  Initialize(isolate);
  if (!ReserveSpace()) {
    return Handle<SharedFunctionInfo>();
  } else {
636
    deserializing_user_code_ = true;
637 638 639 640 641 642 643 644 645 646 647
    HandleScope scope(isolate);
    Handle<SharedFunctionInfo> result;
    {
      DisallowHeapAllocation no_gc;
      Object* root;
      VisitPointer(&root);
      DeserializeDeferredObjects();
      result = Handle<SharedFunctionInfo>(SharedFunctionInfo::cast(root));
    }
    CommitNewInternalizedStrings(isolate);
    return scope.CloseAndEscape(result);
648
  }
649 650 651
}


652
Deserializer::~Deserializer() {
653
  // TODO(svenpanne) Re-enable this assertion when v8 initialization is fixed.
654
  // DCHECK(source_.AtEOF());
655
  attached_objects_.Dispose();
656 657 658 659
}


// This is called on the roots.  It is the driver of the deserialization
660
// process.  It is also called on the body of each function.
661
void Deserializer::VisitPointers(Object** start, Object** end) {
662 663
  // The space must be new space.  Any other space would cause ReadChunk to try
  // to update the remembered using NULL as the address.
664
  ReadData(start, end, NEW_SPACE, NULL);
665 666 667
}


668 669 670 671 672 673 674 675 676 677 678 679
void Deserializer::DeserializeDeferredObjects() {
  for (int code = source_.Get(); code != kSynchronize; code = source_.Get()) {
    int space = code & kSpaceMask;
    DCHECK(space <= kNumberOfSpaces);
    DCHECK(code - space == kNewObject);
    HeapObject* object = GetBackReferencedObject(space);
    int size = source_.GetInt() << kPointerSizeLog2;
    Address obj_address = object->address();
    Object** start = reinterpret_cast<Object**>(obj_address + kPointerSize);
    Object** end = reinterpret_cast<Object**>(obj_address + size);
    bool filled = ReadData(start, end, space, obj_address);
    CHECK(filled);
680 681
    DCHECK(CanBeDeferred(object));
    PostProcessNewObject(object, space);
682 683 684 685
  }
}


686 687 688 689 690
// Used to insert a deserialized internalized string into the string table.
class StringTableInsertionKey : public HashTableKey {
 public:
  explicit StringTableInsertionKey(String* string)
      : string_(string), hash_(HashForObject(string)) {
691
    DCHECK(string->IsInternalizedString());
692 693
  }

694
  bool IsMatch(Object* string) override {
695 696 697 698 699 700 701
    // We know that all entries in a hash table had their hash keys created.
    // Use that knowledge to have fast failure.
    if (hash_ != HashForObject(string)) return false;
    // We want to compare the content of two internalized strings here.
    return string_->SlowEquals(String::cast(string));
  }

702
  uint32_t Hash() override { return hash_; }
703

704
  uint32_t HashForObject(Object* key) override {
705 706 707
    return String::cast(key)->Hash();
  }

708
  MUST_USE_RESULT virtual Handle<Object> AsHandle(Isolate* isolate) override {
709 710 711
    return handle(string_, isolate);
  }

712
 private:
713 714
  String* string_;
  uint32_t hash_;
715
  DisallowHeapAllocation no_gc;
716 717 718
};


719 720
HeapObject* Deserializer::PostProcessNewObject(HeapObject* obj, int space) {
  if (deserializing_user_code()) {
721
    if (obj->IsString()) {
722
      String* string = String::cast(obj);
723 724 725 726 727 728
      // Uninitialize hash field as the hash seed may have changed.
      string->set_hash_field(String::kEmptyHashField);
      if (string->IsInternalizedString()) {
        // Canonicalize the internalized string. If it already exists in the
        // string table, set it to forward to the existing one.
        StringTableInsertionKey key(string);
729 730 731 732 733 734 735 736
        String* canonical = StringTable::LookupKeyIfExists(isolate_, &key);
        if (canonical == NULL) {
          new_internalized_strings_.Add(handle(string));
          return string;
        } else {
          string->SetForwardedInternalizedString(canonical);
          return canonical;
        }
737
      }
738 739 740 741 742
    } else if (obj->IsScript()) {
      // Assign a new script id to avoid collision.
      Script::cast(obj)->set_id(isolate_->heap()->NextScriptId());
    } else {
      DCHECK(CanBeDeferred(obj));
743 744
    }
  }
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
  if (obj->IsAllocationSite()) {
    DCHECK(obj->IsAllocationSite());
    // Allocation sites are present in the snapshot, and must be linked into
    // a list at deserialization time.
    AllocationSite* site = AllocationSite::cast(obj);
    // TODO(mvstanton): consider treating the heap()->allocation_sites_list()
    // as a (weak) root. If this root is relocated correctly, this becomes
    // unnecessary.
    if (isolate_->heap()->allocation_sites_list() == Smi::FromInt(0)) {
      site->set_weak_next(isolate_->heap()->undefined_value());
    } else {
      site->set_weak_next(isolate_->heap()->allocation_sites_list());
    }
    isolate_->heap()->set_allocation_sites_list(site);
  } else if (obj->IsCode()) {
    // We flush all code pages after deserializing the startup snapshot. In that
    // case, we only need to remember code objects in the large object space.
    // When deserializing user code, remember each individual code object.
    if (deserializing_user_code() || space == LO_SPACE) {
      new_code_objects_.Add(Code::cast(obj));
    }
766
  }
767 768
  // Check alignment.
  DCHECK_EQ(0, Heap::GetFillToAlign(obj->address(), obj->RequiredAlignment()));
769
  return obj;
770 771 772
}


773 774 775 776 777 778 779 780 781 782 783
void Deserializer::CommitNewInternalizedStrings(Isolate* isolate) {
  StringTable::EnsureCapacityForDeserialization(
      isolate, new_internalized_strings_.length());
  for (Handle<String> string : new_internalized_strings_) {
    StringTableInsertionKey key(*string);
    DCHECK_NULL(StringTable::LookupKeyIfExists(isolate, &key));
    StringTable::LookupKey(isolate, &key);
  }
}


784 785
HeapObject* Deserializer::GetBackReferencedObject(int space) {
  HeapObject* obj;
786
  BackReference back_reference(source_.GetInt());
787
  if (space == LO_SPACE) {
788 789
    CHECK(back_reference.chunk_index() == 0);
    uint32_t index = back_reference.large_object_index();
790 791 792 793 794 795
    obj = deserialized_large_objects_[index];
  } else {
    DCHECK(space < kNumberOfPreallocatedSpaces);
    uint32_t chunk_index = back_reference.chunk_index();
    DCHECK_LE(chunk_index, current_chunk_[space]);
    uint32_t chunk_offset = back_reference.chunk_offset();
796 797 798 799 800 801 802 803
    Address address = reservations_[space][chunk_index].start + chunk_offset;
    if (next_alignment_ != kWordAligned) {
      int padding = Heap::GetFillToAlign(address, next_alignment_);
      next_alignment_ = kWordAligned;
      DCHECK(padding == 0 || HeapObject::FromAddress(address)->IsFiller());
      address += padding;
    }
    obj = HeapObject::FromAddress(address);
804 805 806 807 808
  }
  if (deserializing_user_code() && obj->IsInternalizedString()) {
    obj = String::cast(obj)->GetForwardedInternalizedString();
  }
  hot_objects_.Add(obj);
809 810 811 812
  return obj;
}


813 814 815
// 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
816 817
// written very late, which means the FreeSpace map is not set up by the
// time we need to use it to mark the space at the end of a page free.
818 819 820
void Deserializer::ReadObject(int space_number, Object** write_back) {
  Address address;
  HeapObject* obj;
821 822 823 824 825 826 827 828 829 830 831 832 833 834
  int size = source_.GetInt() << kObjectAlignmentBits;

  if (next_alignment_ != kWordAligned) {
    int reserved = size + Heap::GetMaximumFillToAlign(next_alignment_);
    address = Allocate(space_number, reserved);
    obj = HeapObject::FromAddress(address);
    // If one of the following assertions fails, then we are deserializing an
    // aligned object when the filler maps have not been deserialized yet.
    // We require filler maps as padding to align the object.
    Heap* heap = isolate_->heap();
    DCHECK(heap->free_space_map()->IsMap());
    DCHECK(heap->one_pointer_filler_map()->IsMap());
    DCHECK(heap->two_pointer_filler_map()->IsMap());
    obj = heap->AlignWithFiller(obj, size, reserved, next_alignment_);
835
    address = obj->address();
836 837 838 839
    next_alignment_ = kWordAligned;
  } else {
    address = Allocate(space_number, size);
    obj = HeapObject::FromAddress(address);
840 841
  }

842
  isolate_->heap()->OnAllocationEvent(obj, size);
843 844
  Object** current = reinterpret_cast<Object**>(address);
  Object** limit = current + (size >> kPointerSizeLog2);
845
  if (FLAG_log_snapshot_positions) {
846
    LOG(isolate_, SnapshotPositionEvent(address, source_.position()));
847
  }
848

849 850
  if (ReadData(current, limit, space_number, address)) {
    // Only post process if object content has not been deferred.
851
    obj = PostProcessNewObject(obj, space_number);
852
  }
853

854 855
  Object* write_back_obj = obj;
  UnalignedCopy(write_back, &write_back_obj);
856
#ifdef DEBUG
857 858 859 860 861
  if (obj->IsCode()) {
    DCHECK(space_number == CODE_SPACE || space_number == LO_SPACE);
  } else {
    DCHECK(space_number != CODE_SPACE);
  }
862
#endif  // DEBUG
863 864
}

865 866 867 868 869

// We know the space requirements before deserialization and can
// pre-allocate that reserved space. During deserialization, all we need
// to do is to bump up the pointer for each space in the reserved
// space. This is also used for fixing back references.
870
// We may have to split up the pre-allocation into several chunks
871 872
// because it would not fit onto a single page. We do not have to keep
// track of when to move to the next chunk. An opcode will signal this.
873 874 875 876 877 878 879 880
// Since multiple large objects cannot be folded into one large object
// space allocation, we have to do an actual allocation when deserializing
// each large object. Instead of tracking offset for back references, we
// reference large objects by index.
Address Deserializer::Allocate(int space_index, int size) {
  if (space_index == LO_SPACE) {
    AlwaysAllocateScope scope(isolate_);
    LargeObjectSpace* lo_space = isolate_->heap()->lo_space();
881
    Executability exec = static_cast<Executability>(source_.Get());
882 883 884 885 886 887 888
    AllocationResult result = lo_space->AllocateRaw(size, exec);
    HeapObject* obj = HeapObject::cast(result.ToObjectChecked());
    deserialized_large_objects_.Add(obj);
    return obj->address();
  } else {
    DCHECK(space_index < kNumberOfPreallocatedSpaces);
    Address address = high_water_[space_index];
889
    DCHECK_NOT_NULL(address);
890 891 892
    high_water_[space_index] += size;
#ifdef DEBUG
    // Assert that the current reserved chunk is still big enough.
893 894
    const Heap::Reservation& reservation = reservations_[space_index];
    int chunk_index = current_chunk_[space_index];
895 896
    CHECK_LE(high_water_[space_index], reservation[chunk_index].end);
#endif
897 898 899 900
    return address;
  }
}

901

902 903 904 905 906 907 908 909 910 911 912
Object** Deserializer::CopyInNativesSource(Vector<const char> source_vector,
                                           Object** current) {
  DCHECK(!isolate_->heap()->deserialization_complete());
  NativesExternalStringResource* resource = new NativesExternalStringResource(
      source_vector.start(), source_vector.length());
  Object* resource_obj = reinterpret_cast<Object*>(resource);
  UnalignedCopy(current++, &resource_obj);
  return current;
}


913
bool Deserializer::ReadData(Object** current, Object** limit, int source_space,
914
                            Address current_object_address) {
915
  Isolate* const isolate = isolate_;
916 917 918
  // Write barrier support costs around 1% in startup time.  In fact there
  // are no new space objects in current boot snapshots, so it's not needed,
  // but that may change.
919 920
  bool write_barrier_needed =
      (current_object_address != NULL && source_space != NEW_SPACE &&
921
       source_space != CODE_SPACE);
922
  while (current < limit) {
923
    byte data = source_.Get();
924
    switch (data) {
925 926
#define CASE_STATEMENT(where, how, within, space_number) \
  case where + how + within + space_number:              \
yangguo's avatar
yangguo committed
927
    STATIC_ASSERT((where & ~kWhereMask) == 0);           \
928 929 930
    STATIC_ASSERT((how & ~kHowToCodeMask) == 0);         \
    STATIC_ASSERT((within & ~kWhereToPointMask) == 0);   \
    STATIC_ASSERT((space_number & ~kSpaceMask) == 0);
931

932
#define CASE_BODY(where, how, within, space_number_if_any)                     \
933 934 935 936 937 938 939 940 941 942 943 944 945
  {                                                                            \
    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) {    \
      ReadObject(space_number, current);                                       \
      emit_write_barrier = (space_number == NEW_SPACE);                        \
    } else {                                                                   \
      Object* new_object = NULL; /* May not be a real Object pointer. */       \
      if (where == kNewObject) {                                               \
        ReadObject(space_number, &new_object);                                 \
yangguo's avatar
yangguo committed
946 947 948 949 950 951 952 953 954
      } else if (where == kBackref) {                                          \
        emit_write_barrier = (space_number == NEW_SPACE);                      \
        new_object = GetBackReferencedObject(data & kSpaceMask);               \
      } else if (where == kBackrefWithSkip) {                                  \
        int skip = source_.GetInt();                                           \
        current = reinterpret_cast<Object**>(                                  \
            reinterpret_cast<Address>(current) + skip);                        \
        emit_write_barrier = (space_number == NEW_SPACE);                      \
        new_object = GetBackReferencedObject(data & kSpaceMask);               \
955
      } else if (where == kRootArray) {                                        \
956
        int root_id = source_.GetInt();                                        \
957 958 959
        new_object = isolate->heap()->roots_array_start()[root_id];            \
        emit_write_barrier = isolate->heap()->InNewSpace(new_object);          \
      } else if (where == kPartialSnapshotCache) {                             \
960
        int cache_index = source_.GetInt();                                    \
961
        new_object = isolate->partial_snapshot_cache()->at(cache_index);       \
962 963
        emit_write_barrier = isolate->heap()->InNewSpace(new_object);          \
      } else if (where == kExternalReference) {                                \
964
        int skip = source_.GetInt();                                           \
965 966
        current = reinterpret_cast<Object**>(                                  \
            reinterpret_cast<Address>(current) + skip);                        \
967
        int reference_id = source_.GetInt();                                   \
968
        Address address = external_reference_table_->address(reference_id);    \
969
        new_object = reinterpret_cast<Object*>(address);                       \
yangguo's avatar
yangguo committed
970 971 972 973 974 975 976
      } else if (where == kAttachedReference) {                                \
        int index = source_.GetInt();                                          \
        DCHECK(deserializing_user_code() || index == kGlobalProxyReference);   \
        new_object = *attached_objects_[index];                                \
        emit_write_barrier = isolate->heap()->InNewSpace(new_object);          \
      } else {                                                                 \
        DCHECK(where == kBuiltin);                                             \
977
        DCHECK(deserializing_user_code());                                     \
978
        int builtin_id = source_.GetInt();                                     \
979 980
        DCHECK_LE(0, builtin_id);                                              \
        DCHECK_LT(builtin_id, Builtins::builtin_count);                        \
981 982 983 984 985 986 987 988 989
        Builtins::Name name = static_cast<Builtins::Name>(builtin_id);         \
        new_object = isolate->builtins()->builtin(name);                       \
        emit_write_barrier = false;                                            \
      }                                                                        \
      if (within == kInnerPointer) {                                           \
        if (space_number != CODE_SPACE || new_object->IsCode()) {              \
          Code* new_code_object = reinterpret_cast<Code*>(new_object);         \
          new_object =                                                         \
              reinterpret_cast<Object*>(new_code_object->instruction_start()); \
990
        } else {                                                               \
991
          DCHECK(space_number == CODE_SPACE);                                  \
992 993
          Cell* cell = Cell::cast(new_object);                                 \
          new_object = reinterpret_cast<Object*>(cell->ValueAddress());        \
994 995
        }                                                                      \
      }                                                                        \
996 997 998 999 1000 1001 1002 1003 1004 1005
      if (how == kFromCode) {                                                  \
        Address location_of_branch_data = reinterpret_cast<Address>(current);  \
        Assembler::deserialization_set_special_target_at(                      \
            location_of_branch_data,                                           \
            Code::cast(HeapObject::FromAddress(current_object_address)),       \
            reinterpret_cast<Address>(new_object));                            \
        location_of_branch_data += Assembler::kSpecialTargetSize;              \
        current = reinterpret_cast<Object**>(location_of_branch_data);         \
        current_was_incremented = true;                                        \
      } else {                                                                 \
1006
        UnalignedCopy(current, &new_object);                                   \
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
      }                                                                        \
    }                                                                          \
    if (emit_write_barrier && write_barrier_needed) {                          \
      Address current_address = reinterpret_cast<Address>(current);            \
      isolate->heap()->RecordWrite(                                            \
          current_object_address,                                              \
          static_cast<int>(current_address - current_object_address));         \
    }                                                                          \
    if (!current_was_incremented) {                                            \
      current++;                                                               \
    }                                                                          \
    break;                                                                     \
  }
1020 1021

// This generates a case and a body for the new space (which has to do extra
verwaest's avatar
verwaest committed
1022 1023
// write barrier handling) and handles the other spaces with fall-through cases
// and one body.
1024 1025 1026 1027 1028 1029 1030
#define ALL_SPACES(where, how, within)           \
  CASE_STATEMENT(where, how, within, NEW_SPACE)  \
  CASE_BODY(where, how, within, NEW_SPACE)       \
  CASE_STATEMENT(where, how, within, OLD_SPACE)  \
  CASE_STATEMENT(where, how, within, CODE_SPACE) \
  CASE_STATEMENT(where, how, within, MAP_SPACE)  \
  CASE_STATEMENT(where, how, within, LO_SPACE)   \
1031
  CASE_BODY(where, how, within, kAnyOldSpace)
1032

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
#define FOUR_CASES(byte_code)             \
  case byte_code:                         \
  case byte_code + 1:                     \
  case byte_code + 2:                     \
  case byte_code + 3:

#define SIXTEEN_CASES(byte_code)          \
  FOUR_CASES(byte_code)                   \
  FOUR_CASES(byte_code + 4)               \
  FOUR_CASES(byte_code + 8)               \
  FOUR_CASES(byte_code + 12)
1044

1045 1046 1047 1048
#define SINGLE_CASE(where, how, within, space) \
  CASE_STATEMENT(where, how, within, space)    \
  CASE_BODY(where, how, within, space)

1049 1050
      // Deserialize a new object and write a pointer to it to the current
      // object.
1051
      ALL_SPACES(kNewObject, kPlain, kStartOfObject)
1052 1053 1054
      // Support for direct instruction pointers in functions.  It's an inner
      // pointer because it points at the entry point, not at the start of the
      // code object.
1055
      SINGLE_CASE(kNewObject, kPlain, kInnerPointer, CODE_SPACE)
1056 1057
      // Deserialize a new code object and write a pointer to its first
      // instruction to the current code object.
1058
      ALL_SPACES(kNewObject, kFromCode, kInnerPointer)
1059 1060 1061
      // 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)
1062
      ALL_SPACES(kBackrefWithSkip, kPlain, kStartOfObject)
1063
#if defined(V8_TARGET_ARCH_MIPS) || defined(V8_TARGET_ARCH_MIPS64) || \
1064
    defined(V8_TARGET_ARCH_PPC) || V8_EMBEDDED_CONSTANT_POOL
1065
      // Deserialize a new object from pointer found in code and write
1066
      // a pointer to it to the current object. Required only for MIPS, PPC or
1067
      // ARM with embedded constant pool, and omitted on the other architectures
1068
      // because it is fully unrolled and would cause bloat.
1069
      ALL_SPACES(kNewObject, kFromCode, kStartOfObject)
1070 1071
      // Find a recently deserialized code object using its offset from the
      // current allocation point and write a pointer to it to the current
1072
      // object. Required only for MIPS, PPC or ARM with embedded constant pool.
1073
      ALL_SPACES(kBackref, kFromCode, kStartOfObject)
1074
      ALL_SPACES(kBackrefWithSkip, kFromCode, kStartOfObject)
1075
#endif
1076 1077
      // Find a recently deserialized code object using its offset from the
      // current allocation point and write a pointer to its first instruction
1078 1079
      // to the current code object or the instruction pointer in a function
      // object.
1080
      ALL_SPACES(kBackref, kFromCode, kInnerPointer)
1081
      ALL_SPACES(kBackrefWithSkip, kFromCode, kInnerPointer)
1082
      ALL_SPACES(kBackref, kPlain, kInnerPointer)
1083
      ALL_SPACES(kBackrefWithSkip, kPlain, kInnerPointer)
1084 1085
      // Find an object in the roots array and write a pointer to it to the
      // current object.
1086
      SINGLE_CASE(kRootArray, kPlain, kStartOfObject, 0)
1087
#if defined(V8_TARGET_ARCH_MIPS) || defined(V8_TARGET_ARCH_MIPS64) || \
1088
    defined(V8_TARGET_ARCH_PPC) || V8_EMBEDDED_CONSTANT_POOL
1089
      // Find an object in the roots array and write a pointer to it to in code.
1090
      SINGLE_CASE(kRootArray, kFromCode, kStartOfObject, 0)
1091
#endif
1092 1093
      // Find an object in the partial snapshots cache and write a pointer to it
      // to the current object.
1094
      SINGLE_CASE(kPartialSnapshotCache, kPlain, kStartOfObject, 0)
1095 1096
      // Find an code entry in the partial snapshots cache and
      // write a pointer to it to the current object.
1097
      SINGLE_CASE(kPartialSnapshotCache, kPlain, kInnerPointer, 0)
1098 1099
      // Find an external reference and write a pointer to it to the current
      // object.
1100
      SINGLE_CASE(kExternalReference, kPlain, kStartOfObject, 0)
1101 1102
      // Find an external reference and write a pointer to it in the current
      // code object.
1103
      SINGLE_CASE(kExternalReference, kFromCode, kStartOfObject, 0)
1104 1105
      // Find an object in the attached references and write a pointer to it to
      // the current object.
1106 1107 1108
      SINGLE_CASE(kAttachedReference, kPlain, kStartOfObject, 0)
      SINGLE_CASE(kAttachedReference, kPlain, kInnerPointer, 0)
      SINGLE_CASE(kAttachedReference, kFromCode, kInnerPointer, 0)
yangguo's avatar
yangguo committed
1109
      // Find a builtin and write a pointer to it to the current object.
1110 1111 1112
      SINGLE_CASE(kBuiltin, kPlain, kStartOfObject, 0)
      SINGLE_CASE(kBuiltin, kPlain, kInnerPointer, 0)
      SINGLE_CASE(kBuiltin, kFromCode, kInnerPointer, 0)
1113 1114 1115 1116 1117

#undef CASE_STATEMENT
#undef CASE_BODY
#undef ALL_SPACES

1118
      case kSkip: {
1119
        int size = source_.GetInt();
1120 1121
        current = reinterpret_cast<Object**>(
            reinterpret_cast<intptr_t>(current) + size);
1122 1123 1124
        break;
      }

1125
      case kInternalReferenceEncoded:
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
      case kInternalReference: {
        // Internal reference address is not encoded via skip, but by offset
        // from code entry.
        int pc_offset = source_.GetInt();
        int target_offset = source_.GetInt();
        Code* code =
            Code::cast(HeapObject::FromAddress(current_object_address));
        DCHECK(0 <= pc_offset && pc_offset <= code->instruction_size());
        DCHECK(0 <= target_offset && target_offset <= code->instruction_size());
        Address pc = code->entry() + pc_offset;
        Address target = code->entry() + target_offset;
1137 1138 1139 1140
        Assembler::deserialization_set_target_internal_reference_at(
            pc, target, data == kInternalReference
                            ? RelocInfo::INTERNAL_REFERENCE
                            : RelocInfo::INTERNAL_REFERENCE_ENCODED);
1141 1142 1143
        break;
      }

yangguo's avatar
yangguo committed
1144
      case kNop:
1145
        break;
1146

1147
      case kNextChunk: {
1148
        int space = source_.Get();
1149 1150 1151 1152 1153 1154 1155
        DCHECK(space < kNumberOfPreallocatedSpaces);
        int chunk_index = current_chunk_[space];
        const Heap::Reservation& reservation = reservations_[space];
        // Make sure the current chunk is indeed exhausted.
        CHECK_EQ(reservation[chunk_index].end, high_water_[space]);
        // Move to next reserved chunk.
        chunk_index = ++current_chunk_[space];
1156
        CHECK_LT(chunk_index, reservation.length());
1157 1158 1159 1160
        high_water_[space] = reservation[chunk_index].start;
        break;
      }

1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
      case kDeferred: {
        // Deferred can only occur right after the heap object header.
        DCHECK(current == reinterpret_cast<Object**>(current_object_address +
                                                     kPointerSize));
        HeapObject* obj = HeapObject::FromAddress(current_object_address);
        // If the deferred object is a map, its instance type may be used
        // during deserialization. Initialize it with a temporary value.
        if (obj->IsMap()) Map::cast(obj)->set_instance_type(FILLER_TYPE);
        current = limit;
        return false;
      }

yangguo's avatar
yangguo committed
1173 1174 1175 1176 1177 1178
      case kSynchronize:
        // If we get here then that indicates that you have a mismatch between
        // the number of GC roots when serializing and deserializing.
        CHECK(false);
        break;

1179 1180 1181 1182 1183 1184 1185 1186
      case kNativesStringResource:
        current = CopyInNativesSource(Natives::GetScriptSource(source_.Get()),
                                      current);
        break;

      case kCodeStubNativesStringResource:
        current = CopyInNativesSource(
            CodeStubNatives::GetScriptSource(source_.Get()), current);
yangguo's avatar
yangguo committed
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
        break;

      // Deserialize raw data of variable length.
      case kVariableRawData: {
        int size_in_bytes = source_.GetInt();
        byte* raw_data_out = reinterpret_cast<byte*>(current);
        source_.CopyRaw(raw_data_out, size_in_bytes);
        break;
      }

      case kVariableRepeat: {
        int repeats = source_.GetInt();
        Object* object = current[-1];
        DCHECK(!isolate->heap()->InNewSpace(object));
        for (int i = 0; i < repeats; i++) UnalignedCopy(current++, &object);
        break;
      }

1205 1206 1207 1208 1209 1210 1211 1212 1213
      case kAlignmentPrefix:
      case kAlignmentPrefix + 1:
      case kAlignmentPrefix + 2: {
        DCHECK_EQ(kWordAligned, next_alignment_);
        next_alignment_ =
            static_cast<AllocationAlignment>(data - (kAlignmentPrefix - 1));
        break;
      }

yangguo's avatar
yangguo committed
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
      STATIC_ASSERT(kNumberOfRootArrayConstants == Heap::kOldSpaceRoots);
      STATIC_ASSERT(kNumberOfRootArrayConstants == 32);
      SIXTEEN_CASES(kRootArrayConstantsWithSkip)
      SIXTEEN_CASES(kRootArrayConstantsWithSkip + 16) {
        int skip = source_.GetInt();
        current = reinterpret_cast<Object**>(
            reinterpret_cast<intptr_t>(current) + skip);
        // Fall through.
      }

      SIXTEEN_CASES(kRootArrayConstants)
      SIXTEEN_CASES(kRootArrayConstants + 16) {
        int root_id = data & kRootArrayConstantsMask;
        Object* object = isolate->heap()->roots_array_start()[root_id];
        DCHECK(!isolate->heap()->InNewSpace(object));
        UnalignedCopy(current++, &object);
        break;
      }

      STATIC_ASSERT(kNumberOfHotObjects == 8);
1234 1235
      FOUR_CASES(kHotObjectWithSkip)
      FOUR_CASES(kHotObjectWithSkip + 4) {
1236
        int skip = source_.GetInt();
1237 1238 1239 1240
        current = reinterpret_cast<Object**>(
            reinterpret_cast<Address>(current) + skip);
        // Fall through.
      }
yangguo's avatar
yangguo committed
1241

1242 1243
      FOUR_CASES(kHotObject)
      FOUR_CASES(kHotObject + 4) {
yangguo's avatar
yangguo committed
1244
        int index = data & kHotObjectMask;
1245 1246 1247
        Object* hot_object = hot_objects_.Get(index);
        UnalignedCopy(current, &hot_object);
        if (write_barrier_needed && isolate->heap()->InNewSpace(hot_object)) {
1248 1249 1250 1251 1252 1253 1254 1255 1256
          Address current_address = reinterpret_cast<Address>(current);
          isolate->heap()->RecordWrite(
              current_object_address,
              static_cast<int>(current_address - current_object_address));
        }
        current++;
        break;
      }

yangguo's avatar
yangguo committed
1257 1258 1259 1260 1261 1262 1263 1264 1265
      // Deserialize raw data of fixed length from 1 to 32 words.
      STATIC_ASSERT(kNumberOfFixedRawData == 32);
      SIXTEEN_CASES(kFixedRawData)
      SIXTEEN_CASES(kFixedRawData + 16) {
        byte* raw_data_out = reinterpret_cast<byte*>(current);
        int size_in_bytes = (data - kFixedRawDataStart) << kPointerSizeLog2;
        source_.CopyRaw(raw_data_out, size_in_bytes);
        current = reinterpret_cast<Object**>(raw_data_out + size_in_bytes);
        break;
1266
      }
1267

yangguo's avatar
yangguo committed
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
      STATIC_ASSERT(kNumberOfFixedRepeat == 16);
      SIXTEEN_CASES(kFixedRepeat) {
        int repeats = data - kFixedRepeatStart;
        Object* object;
        UnalignedCopy(&object, current - 1);
        DCHECK(!isolate->heap()->InNewSpace(object));
        for (int i = 0; i < repeats; i++) UnalignedCopy(current++, &object);
        break;
      }

#undef SIXTEEN_CASES
#undef FOUR_CASES
1280
#undef SINGLE_CASE
yangguo's avatar
yangguo committed
1281

1282
      default:
1283
        CHECK(false);
1284 1285
    }
  }
1286
  CHECK_EQ(limit, current);
1287
  return true;
1288 1289 1290
}


1291 1292 1293
Serializer::Serializer(Isolate* isolate, SnapshotByteSink* sink)
    : isolate_(isolate),
      sink_(sink),
1294
      external_reference_encoder_(isolate),
1295
      root_index_map_(isolate),
1296
      recursion_depth_(0),
1297
      code_address_map_(NULL),
1298
      large_objects_total_size_(0),
1299
      seen_large_objects_index_(0) {
1300 1301
  // The serializer is meant to be used only to generate initial heap images
  // from a context in which there is only one isolate.
1302 1303 1304 1305 1306
  for (int i = 0; i < kNumberOfPreallocatedSpaces; i++) {
    pending_chunk_[i] = 0;
    max_chunk_size_[i] = static_cast<uint32_t>(
        MemoryAllocator::PageAreaSize(static_cast<AllocationSpace>(i)));
  }
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320

#ifdef OBJECT_PRINT
  if (FLAG_serialization_statistics) {
    instance_type_count_ = NewArray<int>(kInstanceTypes);
    instance_type_size_ = NewArray<size_t>(kInstanceTypes);
    for (int i = 0; i < kInstanceTypes; i++) {
      instance_type_count_[i] = 0;
      instance_type_size_[i] = 0;
    }
  } else {
    instance_type_count_ = NULL;
    instance_type_size_ = NULL;
  }
#endif  // OBJECT_PRINT
1321 1322 1323
}


1324
Serializer::~Serializer() {
1325
  if (code_address_map_ != NULL) delete code_address_map_;
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
#ifdef OBJECT_PRINT
  if (instance_type_count_ != NULL) {
    DeleteArray(instance_type_count_);
    DeleteArray(instance_type_size_);
  }
#endif  // OBJECT_PRINT
}


#ifdef OBJECT_PRINT
1336 1337
void Serializer::CountInstanceType(Map* map, int size) {
  int instance_type = map->instance_type();
1338
  instance_type_count_[instance_type]++;
1339
  instance_type_size_[instance_type] += size;
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
}
#endif  // OBJECT_PRINT


void Serializer::OutputStatistics(const char* name) {
  if (!FLAG_serialization_statistics) return;
  PrintF("%s:\n", name);
  PrintF("  Spaces (bytes):\n");
  for (int space = 0; space < kNumberOfSpaces; space++) {
    PrintF("%16s", AllocationSpaceName(static_cast<AllocationSpace>(space)));
  }
  PrintF("\n");
  for (int space = 0; space < kNumberOfPreallocatedSpaces; space++) {
    size_t s = pending_chunk_[space];
    for (uint32_t chunk_size : completed_chunks_[space]) s += chunk_size;
    PrintF("%16" V8_PTR_PREFIX "d", s);
  }
  PrintF("%16d\n", large_objects_total_size_);
#ifdef OBJECT_PRINT
  PrintF("  Instance types (count and bytes):\n");
#define PRINT_INSTANCE_TYPE(Name)                                          \
  if (instance_type_count_[Name]) {                                        \
    PrintF("%10d %10" V8_PTR_PREFIX "d  %s\n", instance_type_count_[Name], \
           instance_type_size_[Name], #Name);                              \
  }
  INSTANCE_TYPE_LIST(PRINT_INSTANCE_TYPE)
#undef PRINT_INSTANCE_TYPE
  PrintF("\n");
#endif  // OBJECT_PRINT
1369 1370 1371
}


1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
void Serializer::SerializeDeferredObjects() {
  while (deferred_objects_.length() > 0) {
    HeapObject* obj = deferred_objects_.RemoveLast();
    ObjectSerializer obj_serializer(this, obj, sink_, kPlain, kStartOfObject);
    obj_serializer.SerializeDeferred();
  }
  sink_->Put(kSynchronize, "Finished with deferred objects");
}


1382
void StartupSerializer::SerializeStrongReferences() {
1383
  Isolate* isolate = this->isolate();
1384
  // No active threads.
1385
  CHECK_NULL(isolate->thread_manager()->FirstThreadStateInUse());
1386
  // No active or weak handles.
1387 1388
  CHECK(isolate->handle_scope_implementer()->blocks()->is_empty());
  CHECK_EQ(0, isolate->global_handles()->NumberOfWeakHandles());
1389
  CHECK_EQ(0, isolate->eternal_handles()->NumberOfHandles());
1390
  // We don't support serializing installed extensions.
1391
  CHECK(!isolate->has_installed_extensions());
1392
  isolate->heap()->IterateSmiRoots(this);
1393
  isolate->heap()->IterateStrongRoots(this, VISIT_ONLY_STRONG);
1394 1395 1396
}


1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
void StartupSerializer::VisitPointers(Object** start, Object** end) {
  for (Object** current = start; current < end; current++) {
    if (start == isolate()->heap()->roots_array_start()) {
      root_index_wave_front_ =
          Max(root_index_wave_front_, static_cast<intptr_t>(current - start));
    }
    if (ShouldBeSkipped(current)) {
      sink_->Put(kSkip, "Skip");
      sink_->PutInt(kPointerSize, "SkipOneWord");
    } else if ((*current)->IsSmi()) {
1407
      sink_->Put(kOnePointerRawData, "Smi");
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
      for (int i = 0; i < kPointerSize; i++) {
        sink_->Put(reinterpret_cast<byte*>(current)[i], "Byte");
      }
    } else {
      SerializeObject(HeapObject::cast(*current), kPlain, kStartOfObject, 0);
    }
  }
}


1418
void PartialSerializer::Serialize(Object** o) {
1419 1420 1421
  if ((*o)->IsContext()) {
    Context* context = Context::cast(*o);
    global_object_ = context->global_object();
1422
    back_reference_map()->AddGlobalProxy(context->global_proxy());
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
    // The bootstrap snapshot has a code-stub context. When serializing the
    // partial snapshot, it is chained into the weak context list on the isolate
    // and it's next context pointer may point to the code-stub context.  Clear
    // it before serializing, it will get re-added to the context list
    // explicitly when it's loaded.
    if (context->IsNativeContext()) {
      context->set(Context::NEXT_CONTEXT_LINK,
                   isolate_->heap()->undefined_value());
      DCHECK(!context->global_object()->IsUndefined());
      DCHECK(!context->builtins()->IsUndefined());
    }
1434
  }
1435
  VisitPointer(o);
1436
  SerializeDeferredObjects();
1437
  SerializeOutdatedContextsAsFixedArray();
1438
  Pad();
1439 1440 1441
}


1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
void PartialSerializer::SerializeOutdatedContextsAsFixedArray() {
  int length = outdated_contexts_.length();
  if (length == 0) {
    FixedArray* empty = isolate_->heap()->empty_fixed_array();
    SerializeObject(empty, kPlain, kStartOfObject, 0);
  } else {
    // Serialize an imaginary fixed array containing outdated contexts.
    int size = FixedArray::SizeFor(length);
    Allocate(NEW_SPACE, size);
    sink_->Put(kNewObject + NEW_SPACE, "emulated FixedArray");
    sink_->PutInt(size >> kObjectAlignmentBits, "FixedArray size in words");
    Map* map = isolate_->heap()->fixed_array_map();
    SerializeObject(map, kPlain, kStartOfObject, 0);
    Smi* length_smi = Smi::FromInt(length);
    sink_->Put(kOnePointerRawData, "Smi");
    for (int i = 0; i < kPointerSize; i++) {
      sink_->Put(reinterpret_cast<byte*>(&length_smi)[i], "Byte");
    }
    for (int i = 0; i < length; i++) {
1461 1462 1463 1464
      Context* context = outdated_contexts_[i];
      BackReference back_reference = back_reference_map_.Lookup(context);
      sink_->Put(kBackref + back_reference.space(), "BackRef");
      PutBackReference(context, back_reference);
1465 1466 1467 1468 1469
    }
  }
}


1470 1471 1472 1473 1474 1475 1476 1477
bool Serializer::ShouldBeSkipped(Object** current) {
  Object** roots = isolate()->heap()->roots_array_start();
  return current == &roots[Heap::kStoreBufferTopRootIndex]
      || current == &roots[Heap::kStackLimitRootIndex]
      || current == &roots[Heap::kRealStackLimitRootIndex];
}


1478
void Serializer::VisitPointers(Object** start, Object** end) {
1479
  for (Object** current = start; current < end; current++) {
1480
    if ((*current)->IsSmi()) {
1481
      sink_->Put(kOnePointerRawData, "Smi");
1482 1483 1484 1485
      for (int i = 0; i < kPointerSize; i++) {
        sink_->Put(reinterpret_cast<byte*>(current)[i], "Byte");
      }
    } else {
1486
      SerializeObject(HeapObject::cast(*current), kPlain, kStartOfObject, 0);
1487
    }
1488 1489 1490 1491
  }
}


1492 1493
void Serializer::EncodeReservations(
    List<SerializedData::Reservation>* out) const {
1494
  for (int i = 0; i < kNumberOfPreallocatedSpaces; i++) {
1495 1496 1497 1498
    for (int j = 0; j < completed_chunks_[i].length(); j++) {
      out->Add(SerializedData::Reservation(completed_chunks_[i][j]));
    }

1499
    if (pending_chunk_[i] > 0 || completed_chunks_[i].length() == 0) {
1500
      out->Add(SerializedData::Reservation(pending_chunk_[i]));
1501
    }
1502
    out->last().mark_as_last();
1503
  }
1504 1505 1506

  out->Add(SerializedData::Reservation(large_objects_total_size_));
  out->last().mark_as_last();
1507 1508 1509
}


1510 1511
// 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
1512 1513 1514 1515 1516 1517
// snapshot 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.
1518 1519
void SerializerDeserializer::Iterate(Isolate* isolate,
                                     ObjectVisitor* visitor) {
1520
  if (isolate->serializer_enabled()) return;
1521 1522 1523 1524 1525
  List<Object*>* cache = isolate->partial_snapshot_cache();
  for (int i = 0;; ++i) {
    // Extend the array ready to get a value when deserializing.
    if (cache->length() <= i) cache->Add(Smi::FromInt(0));
    visitor->VisitPointer(&cache->at(i));
1526 1527
    // Sentinel is the undefined object, which is a root so it will not normally
    // be found in the cache.
1528
    if (cache->at(i)->IsUndefined()) break;
1529
  }
1530 1531 1532 1533
}


int PartialSerializer::PartialSnapshotCacheIndex(HeapObject* heap_object) {
1534
  Isolate* isolate = this->isolate();
1535
  List<Object*>* cache = isolate->partial_snapshot_cache();
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
  int new_index = cache->length();

  int index = partial_cache_index_map_.LookupOrInsert(heap_object, new_index);
  if (index == PartialCacheIndexMap::kInvalidIndex) {
    // 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.
    cache->Add(heap_object);
    startup_serializer_->VisitPointer(reinterpret_cast<Object**>(&heap_object));
    // We don't recurse from the startup snapshot generator into the partial
    // snapshot generator.
    return new_index;
1548
  }
1549
  return index;
1550 1551 1552
}


1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
#ifdef DEBUG
bool Serializer::BackReferenceIsAlreadyAllocated(BackReference reference) {
  DCHECK(reference.is_valid());
  DCHECK(!reference.is_source());
  DCHECK(!reference.is_global_proxy());
  AllocationSpace space = reference.space();
  int chunk_index = reference.chunk_index();
  if (space == LO_SPACE) {
    return chunk_index == 0 &&
           reference.large_object_index() < seen_large_objects_index_;
  } else if (chunk_index == completed_chunks_[space].length()) {
    return reference.chunk_offset() < pending_chunk_[space];
  } else {
    return chunk_index < completed_chunks_[space].length() &&
           reference.chunk_offset() < completed_chunks_[space][chunk_index];
  }
}
#endif  // DEBUG


1573 1574 1575 1576 1577 1578
bool Serializer::SerializeKnownObject(HeapObject* obj, HowToCode how_to_code,
                                      WhereToPoint where_to_point, int skip) {
  if (how_to_code == kPlain && where_to_point == kStartOfObject) {
    // Encode a reference to a hot object by its index in the working set.
    int index = hot_objects_.Find(obj);
    if (index != HotObjectsList::kNotFound) {
yangguo's avatar
yangguo committed
1579
      DCHECK(index >= 0 && index < kNumberOfHotObjects);
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
      if (FLAG_trace_serializer) {
        PrintF(" Encoding hot object %d:", index);
        obj->ShortPrint();
        PrintF("\n");
      }
      if (skip != 0) {
        sink_->Put(kHotObjectWithSkip + index, "HotObjectWithSkip");
        sink_->PutInt(skip, "HotObjectSkipDistance");
      } else {
        sink_->Put(kHotObject + index, "HotObject");
      }
      return true;
    }
1593
  }
1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
  BackReference back_reference = back_reference_map_.Lookup(obj);
  if (back_reference.is_valid()) {
    // 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 fromthe start of the deserialized objects or as an offset
    // backwards from thecurrent allocation pointer.
    if (back_reference.is_source()) {
      FlushSkip(skip);
      if (FLAG_trace_serializer) PrintF(" Encoding source object\n");
      DCHECK(how_to_code == kPlain && where_to_point == kStartOfObject);
1604 1605 1606 1607 1608 1609 1610 1611
      sink_->Put(kAttachedReference + kPlain + kStartOfObject, "Source");
      sink_->PutInt(kSourceObjectReference, "kSourceObjectReference");
    } else if (back_reference.is_global_proxy()) {
      FlushSkip(skip);
      if (FLAG_trace_serializer) PrintF(" Encoding global proxy\n");
      DCHECK(how_to_code == kPlain && where_to_point == kStartOfObject);
      sink_->Put(kAttachedReference + kPlain + kStartOfObject, "Global Proxy");
      sink_->PutInt(kGlobalProxyReference, "kGlobalProxyReference");
1612 1613 1614 1615 1616 1617
    } else {
      if (FLAG_trace_serializer) {
        PrintF(" Encoding back reference to: ");
        obj->ShortPrint();
        PrintF("\n");
      }
1618

1619
      PutAlignmentPrefix(obj);
1620 1621 1622 1623 1624 1625 1626 1627
      AllocationSpace space = back_reference.space();
      if (skip == 0) {
        sink_->Put(kBackref + how_to_code + where_to_point + space, "BackRef");
      } else {
        sink_->Put(kBackrefWithSkip + how_to_code + where_to_point + space,
                   "BackRefWithSkip");
        sink_->PutInt(skip, "BackRefSkipDistance");
      }
1628
      PutBackReference(obj, back_reference);
1629 1630 1631 1632
    }
    return true;
  }
  return false;
1633 1634 1635
}


1636 1637
void StartupSerializer::SerializeObject(HeapObject* obj, HowToCode how_to_code,
                                        WhereToPoint where_to_point, int skip) {
1638 1639 1640 1641
  // Make sure that all functions are derived from the code-stub context
  DCHECK(!obj->IsJSFunction() ||
         JSFunction::cast(obj)->GetCreationContext() ==
             isolate()->heap()->code_stub_context());
1642

1643 1644 1645 1646 1647 1648
  int root_index = root_index_map_.Lookup(obj);
  // We can only encode roots as such if it has already been serialized.
  // That applies to root indices below the wave front.
  if (root_index != RootIndexMap::kInvalidRootIndex &&
      root_index < root_index_wave_front_) {
    PutRoot(root_index, obj, how_to_code, where_to_point, skip);
1649 1650 1651
    return;
  }

1652 1653 1654 1655
  if (obj->IsCode() && Code::cast(obj)->kind() == Code::FUNCTION) {
    obj = isolate()->builtins()->builtin(Builtins::kCompileLazy);
  }

1656
  if (SerializeKnownObject(obj, how_to_code, where_to_point, skip)) return;
1657

1658
  FlushSkip(skip);
1659 1660 1661 1662 1663

  // Object has not yet been serialized.  Serialize it here.
  ObjectSerializer object_serializer(this, obj, sink_, how_to_code,
                                     where_to_point);
  object_serializer.Serialize();
1664 1665 1666
}


1667
void StartupSerializer::SerializeWeakReferencesAndDeferred() {
1668
  // This phase comes right after the serialization (of the snapshot).
1669 1670 1671 1672
  // After we have done the partial serialization the partial snapshot cache
  // will contain some references needed to decode the partial snapshot.  We
  // add one entry with 'undefined' which is the sentinel that the deserializer
  // uses to know it is done deserializing the array.
1673
  Object* undefined = isolate()->heap()->undefined_value();
1674
  VisitPointer(&undefined);
1675
  isolate()->heap()->IterateWeakRoots(this, VISIT_ALL);
1676
  SerializeDeferredObjects();
1677
  Pad();
1678 1679 1680
}


1681 1682 1683
void Serializer::PutRoot(int root_index,
                         HeapObject* object,
                         SerializerDeserializer::HowToCode how_to_code,
1684 1685
                         SerializerDeserializer::WhereToPoint where_to_point,
                         int skip) {
1686 1687 1688 1689 1690 1691
  if (FLAG_trace_serializer) {
    PrintF(" Encoding root %d:", root_index);
    object->ShortPrint();
    PrintF("\n");
  }

yangguo's avatar
yangguo committed
1692 1693
  if (how_to_code == kPlain && where_to_point == kStartOfObject &&
      root_index < kNumberOfRootArrayConstants &&
1694
      !isolate()->heap()->InNewSpace(object)) {
1695
    if (skip == 0) {
yangguo's avatar
yangguo committed
1696
      sink_->Put(kRootArrayConstants + root_index, "RootConstant");
1697
    } else {
yangguo's avatar
yangguo committed
1698
      sink_->Put(kRootArrayConstantsWithSkip + root_index, "RootConstant");
1699
      sink_->PutInt(skip, "SkipInPutRoot");
1700 1701
    }
  } else {
1702
    FlushSkip(skip);
1703 1704 1705 1706 1707 1708
    sink_->Put(kRootArray + how_to_code + where_to_point, "RootSerialization");
    sink_->PutInt(root_index, "root_index");
  }
}


1709 1710 1711 1712 1713 1714 1715
void Serializer::PutBackReference(HeapObject* object, BackReference reference) {
  DCHECK(BackReferenceIsAlreadyAllocated(reference));
  sink_->PutInt(reference.reference(), "BackRefValue");
  hot_objects_.Add(object);
}


1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727
int Serializer::PutAlignmentPrefix(HeapObject* object) {
  AllocationAlignment alignment = object->RequiredAlignment();
  if (alignment != kWordAligned) {
    DCHECK(1 <= alignment && alignment <= 3);
    byte prefix = (kAlignmentPrefix - 1) + alignment;
    sink_->Put(prefix, "Alignment");
    return Heap::GetMaximumFillToAlign(alignment);
  }
  return 0;
}


1728 1729 1730
void PartialSerializer::SerializeObject(HeapObject* obj, HowToCode how_to_code,
                                        WhereToPoint where_to_point, int skip) {
  if (obj->IsMap()) {
1731 1732
    // The code-caches link to context-specific code objects, which
    // the startup and context serializes cannot currently handle.
1733
    DCHECK(Map::cast(obj)->code_cache() == obj->GetHeap()->empty_fixed_array());
1734 1735
  }

1736 1737 1738
  // Replace typed arrays by undefined.
  if (obj->IsJSTypedArray()) obj = isolate_->heap()->undefined_value();

1739 1740 1741
  int root_index = root_index_map_.Lookup(obj);
  if (root_index != RootIndexMap::kInvalidRootIndex) {
    PutRoot(root_index, obj, how_to_code, where_to_point, skip);
1742 1743 1744
    return;
  }

1745
  if (ShouldBeInThePartialSnapshotCache(obj)) {
1746
    FlushSkip(skip);
1747

1748
    int cache_index = PartialSnapshotCacheIndex(obj);
1749 1750
    sink_->Put(kPartialSnapshotCache + how_to_code + where_to_point,
               "PartialSnapshotCache");
1751 1752 1753 1754 1755 1756 1757
    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.
1758
  DCHECK(!startup_serializer_->back_reference_map()->Lookup(obj).is_valid());
1759 1760
  // All the internalized strings that the partial snapshot needs should be
  // either in the root table or in the partial snapshot cache.
1761
  DCHECK(!obj->IsInternalizedString());
1762

1763 1764 1765
  if (SerializeKnownObject(obj, how_to_code, where_to_point, skip)) return;

  FlushSkip(skip);
1766

1767 1768 1769 1770 1771 1772
  // Clear literal boilerplates.
  if (obj->IsJSFunction() && !JSFunction::cast(obj)->shared()->bound()) {
    FixedArray* literals = JSFunction::cast(obj)->literals();
    for (int i = 0; i < literals->length(); i++) literals->set_undefined(i);
  }

1773 1774 1775
  // Object has not yet been serialized.  Serialize it here.
  ObjectSerializer serializer(this, obj, sink_, how_to_code, where_to_point);
  serializer.Serialize();
1776 1777 1778 1779 1780

  if (obj->IsContext() &&
      Context::cast(obj)->global_object() == global_object_) {
    // Context refers to the current global object. This reference will
    // become outdated after deserialization.
1781
    outdated_contexts_.Add(Context::cast(obj));
1782
  }
1783 1784 1785
}


1786 1787
void Serializer::ObjectSerializer::SerializePrologue(AllocationSpace space,
                                                     int size, Map* map) {
1788 1789 1790 1791 1792 1793 1794 1795
  if (serializer_->code_address_map_) {
    const char* code_name =
        serializer_->code_address_map_->Lookup(object_->address());
    LOG(serializer_->isolate_,
        CodeNameEvent(object_->address(), sink_->Position(), code_name));
    LOG(serializer_->isolate_,
        SnapshotPositionEvent(object_->address(), sink_->Position()));
  }
1796

1797
  BackReference back_reference;
1798
  if (space == LO_SPACE) {
1799
    sink_->Put(kNewObject + reference_representation_ + space,
1800 1801
               "NewLargeObject");
    sink_->PutInt(size >> kObjectAlignmentBits, "ObjectSizeInWords");
1802
    if (object_->IsCode()) {
1803
      sink_->Put(EXECUTABLE, "executable large object");
1804
    } else {
1805
      sink_->Put(NOT_EXECUTABLE, "not executable large object");
1806
    }
1807
    back_reference = serializer_->AllocateLargeObject(size);
1808
  } else {
1809 1810
    int fill = serializer_->PutAlignmentPrefix(object_);
    back_reference = serializer_->Allocate(space, size + fill);
1811
    sink_->Put(kNewObject + reference_representation_ + space, "NewObject");
1812
    sink_->PutInt(size >> kObjectAlignmentBits, "ObjectSizeInWords");
1813
  }
1814

1815 1816
#ifdef OBJECT_PRINT
  if (FLAG_serialization_statistics) {
1817
    serializer_->CountInstanceType(map, size);
1818 1819 1820
  }
#endif  // OBJECT_PRINT

1821
  // Mark this object as already serialized.
1822
  serializer_->back_reference_map()->Add(object_, back_reference);
1823 1824

  // Serialize the map (first word of the object).
1825 1826 1827 1828 1829 1830 1831 1832
  serializer_->SerializeObject(map, kPlain, kStartOfObject, 0);
}


void Serializer::ObjectSerializer::SerializeExternalString() {
  // Instead of serializing this as an external string, we serialize
  // an imaginary sequential string with the same content.
  Isolate* isolate = serializer_->isolate();
1833 1834
  DCHECK(object_->IsExternalString());
  DCHECK(object_->map() != isolate->heap()->native_source_string_map());
1835 1836 1837
  ExternalString* string = ExternalString::cast(object_);
  int length = string->length();
  Map* map;
1838 1839 1840
  int content_size;
  int allocation_size;
  const byte* resource;
1841
  // Find the map and size for the imaginary sequential string.
1842
  bool internalized = object_->IsInternalizedString();
1843
  if (object_->IsExternalOneByteString()) {
1844 1845
    map = internalized ? isolate->heap()->one_byte_internalized_string_map()
                       : isolate->heap()->one_byte_string_map();
1846 1847 1848 1849
    allocation_size = SeqOneByteString::SizeFor(length);
    content_size = length * kCharSize;
    resource = reinterpret_cast<const byte*>(
        ExternalOneByteString::cast(string)->resource()->data());
1850
  } else {
1851 1852
    map = internalized ? isolate->heap()->internalized_string_map()
                       : isolate->heap()->string_map();
1853 1854 1855
    allocation_size = SeqTwoByteString::SizeFor(length);
    content_size = length * kShortSize;
    resource = reinterpret_cast<const byte*>(
1856 1857 1858
        ExternalTwoByteString::cast(string)->resource()->data());
  }

1859 1860
  AllocationSpace space = (allocation_size > Page::kMaxRegularHeapObjectSize)
                              ? LO_SPACE
1861
                              : OLD_SPACE;
1862
  SerializePrologue(space, allocation_size, map);
1863 1864

  // Output the rest of the imaginary string.
1865
  int bytes_to_output = allocation_size - HeapObject::kHeaderSize;
1866 1867

  // Output raw data header. Do not bother with common raw length cases here.
yangguo's avatar
yangguo committed
1868
  sink_->Put(kVariableRawData, "RawDataForString");
1869 1870 1871 1872 1873 1874 1875 1876 1877
  sink_->PutInt(bytes_to_output, "length");

  // Serialize string header (except for map).
  Address string_start = string->address();
  for (int i = HeapObject::kHeaderSize; i < SeqString::kHeaderSize; i++) {
    sink_->PutSection(string_start[i], "StringHeader");
  }

  // Serialize string content.
1878
  sink_->PutRaw(resource, content_size, "StringContent");
1879 1880 1881 1882 1883 1884

  // Since the allocation size is rounded up to object alignment, there
  // maybe left-over bytes that need to be padded.
  int padding_size = allocation_size - SeqString::kHeaderSize - content_size;
  DCHECK(0 <= padding_size && padding_size < kObjectAlignment);
  for (int i = 0; i < padding_size; i++) sink_->PutSection(0, "StringPadding");
1885 1886 1887 1888 1889

  sink_->Put(kSkip, "SkipAfterString");
  sink_->PutInt(bytes_to_output, "SkipDistance");
}

1890

1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
// Clear and later restore the next link in the weak cell, if the object is one.
class UnlinkWeakCellScope {
 public:
  explicit UnlinkWeakCellScope(HeapObject* object) : weak_cell_(NULL) {
    if (object->IsWeakCell()) {
      weak_cell_ = WeakCell::cast(object);
      next_ = weak_cell_->next();
      weak_cell_->clear_next(object->GetHeap());
    }
  }

  ~UnlinkWeakCellScope() {
    if (weak_cell_) weak_cell_->set_next(next_, UPDATE_WEAK_WRITE_BARRIER);
  }

 private:
  WeakCell* weak_cell_;
  Object* next_;
  DisallowHeapAllocation no_gc_;
};


1913
void Serializer::ObjectSerializer::Serialize() {
1914 1915 1916 1917 1918 1919
  if (FLAG_trace_serializer) {
    PrintF(" Encoding heap object: ");
    object_->ShortPrint();
    PrintF("\n");
  }

1920 1921 1922
  // We cannot serialize typed array objects correctly.
  DCHECK(!object_->IsJSTypedArray());

1923 1924 1925
  // We don't expect fillers.
  DCHECK(!object_->IsFiller());

1926 1927 1928
  if (object_->IsPrototypeInfo()) {
    Object* prototype_users = PrototypeInfo::cast(object_)->prototype_users();
    if (prototype_users->IsWeakFixedArray()) {
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
      WeakFixedArray* array = WeakFixedArray::cast(prototype_users);
      array->Compact<JSObject::PrototypeRegistryCompactionCallback>();
    }
  }
  // Compaction of a prototype users list can require the registered users
  // to update their remembered slots. That doesn't work if those users
  // have already been serialized themselves. So if this object is a
  // registered user, compact its prototype's user list now.
  if (object_->IsMap()) {
    Map* map = Map::cast(object_);
    if (map->is_prototype_map() && map->prototype_info()->IsPrototypeInfo() &&
        PrototypeInfo::cast(map->prototype_info())->registry_slot() !=
            PrototypeInfo::UNREGISTERED) {
      JSObject* proto = JSObject::cast(map->prototype());
      PrototypeInfo* info = PrototypeInfo::cast(proto->map()->prototype_info());
      WeakFixedArray* array = WeakFixedArray::cast(info->prototype_users());
      array->Compact<JSObject::PrototypeRegistryCompactionCallback>();
1946 1947 1948
    }
  }

1949 1950 1951 1952
  if (object_->IsScript()) {
    // Clear cached line ends.
    Object* undefined = serializer_->isolate()->heap()->undefined_value();
    Script::cast(object_)->set_line_ends(undefined);
1953 1954
    Object* shared_list = Script::cast(object_)->shared_function_infos();
    if (shared_list->IsWeakFixedArray()) {
1955 1956
      WeakFixedArray::cast(shared_list)
          ->Compact<WeakFixedArray::NullCallback>();
1957
    }
1958 1959
  }

1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
  if (object_->IsExternalString()) {
    Heap* heap = serializer_->isolate()->heap();
    if (object_->map() != heap->native_source_string_map()) {
      // Usually we cannot recreate resources for external strings. To work
      // around this, external strings are serialized to look like ordinary
      // sequential strings.
      // The exception are native source code strings, since we can recreate
      // their resources. In that case we fall through and leave it to
      // VisitExternalOneByteString further down.
      SerializeExternalString();
      return;
    }
  }
1973

1974 1975
  int size = object_->Size();
  Map* map = object_->map();
1976 1977 1978
  AllocationSpace space =
      MemoryChunk::FromAddress(object_->address())->owner()->identity();
  SerializePrologue(space, size, map);
1979

1980 1981 1982 1983
  // Serialize the rest of the object.
  CHECK_EQ(0, bytes_processed_so_far_);
  bytes_processed_so_far_ = kPointerSize;

1984 1985 1986 1987 1988 1989 1990 1991 1992
  RecursionScope recursion(serializer_);
  // Objects that are immediately post processed during deserialization
  // cannot be deferred, since post processing requires the object content.
  if (recursion.ExceedsMaximum() && CanBeDeferred(object_)) {
    serializer_->QueueDeferredObject(object_);
    sink_->Put(kDeferred, "Deferring object content");
    return;
  }

1993 1994
  UnlinkWeakCellScope unlink_weak_cell(object_);

1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
  object_->IterateBody(map->instance_type(), size, this);
  OutputRawData(object_->address() + size);
}


void Serializer::ObjectSerializer::SerializeDeferred() {
  if (FLAG_trace_serializer) {
    PrintF(" Encoding deferred heap object: ");
    object_->ShortPrint();
    PrintF("\n");
  }

  int size = object_->Size();
  Map* map = object_->map();
  BackReference reference = serializer_->back_reference_map()->Lookup(object_);

  // Serialize the rest of the object.
  CHECK_EQ(0, bytes_processed_so_far_);
  bytes_processed_so_far_ = kPointerSize;

  sink_->Put(kNewObject + reference.space(), "deferred object");
  serializer_->PutBackReference(object_, reference);
  sink_->PutInt(size >> kPointerSizeLog2, "deferred object size");

2019 2020
  UnlinkWeakCellScope unlink_weak_cell(object_);

2021 2022
  object_->IterateBody(map->instance_type(), size, this);
  OutputRawData(object_->address() + size);
2023 2024 2025
}


2026 2027
void Serializer::ObjectSerializer::VisitPointers(Object** start,
                                                 Object** end) {
2028 2029 2030
  Object** current = start;
  while (current < end) {
    while (current < end && (*current)->IsSmi()) current++;
2031
    if (current < end) OutputRawData(reinterpret_cast<Address>(current));
2032 2033

    while (current < end && !(*current)->IsSmi()) {
2034
      HeapObject* current_contents = HeapObject::cast(*current);
2035
      int root_index = serializer_->root_index_map()->Lookup(current_contents);
2036 2037
      // Repeats are not subject to the write barrier so we can only use
      // immortal immovable root members. They are never in new space.
2038
      if (current != start && root_index != RootIndexMap::kInvalidRootIndex &&
2039
          Heap::RootIsImmortalImmovable(root_index) &&
2040
          current_contents == current[-1]) {
2041
        DCHECK(!serializer_->isolate()->heap()->InNewSpace(current_contents));
2042
        int repeat_count = 1;
2043 2044
        while (&current[repeat_count] < end - 1 &&
               current[repeat_count] == current_contents) {
2045 2046 2047 2048
          repeat_count++;
        }
        current += repeat_count;
        bytes_processed_so_far_ += repeat_count * kPointerSize;
yangguo's avatar
yangguo committed
2049 2050 2051
        if (repeat_count > kNumberOfFixedRepeat) {
          sink_->Put(kVariableRepeat, "VariableRepeat");
          sink_->PutInt(repeat_count, "repeat count");
2052
        } else {
yangguo's avatar
yangguo committed
2053
          sink_->Put(kFixedRepeatStart + repeat_count, "FixedRepeat");
2054 2055
        }
      } else {
2056 2057
        serializer_->SerializeObject(
                current_contents, kPlain, kStartOfObject, 0);
2058 2059 2060
        bytes_processed_so_far_ += kPointerSize;
        current++;
      }
2061
    }
2062 2063 2064 2065
  }
}


2066
void Serializer::ObjectSerializer::VisitEmbeddedPointer(RelocInfo* rinfo) {
2067 2068
  int skip = OutputRawData(rinfo->target_address_address(),
                           kCanReturnSkipInsteadOfSkipping);
2069 2070
  HowToCode how_to_code = rinfo->IsCodedSpecially() ? kFromCode : kPlain;
  Object* object = rinfo->target_object();
2071 2072
  serializer_->SerializeObject(HeapObject::cast(object), how_to_code,
                               kStartOfObject, skip);
2073 2074 2075 2076
  bytes_processed_so_far_ += rinfo->target_address_size();
}


2077
void Serializer::ObjectSerializer::VisitExternalReference(Address* p) {
2078 2079
  int skip = OutputRawData(reinterpret_cast<Address>(p),
                           kCanReturnSkipInsteadOfSkipping);
2080 2081
  sink_->Put(kExternalReference + kPlain + kStartOfObject, "ExternalRef");
  sink_->PutInt(skip, "SkipB4ExternalRef");
2082 2083
  Address target = *p;
  sink_->PutInt(serializer_->EncodeExternalReference(target), "reference id");
2084
  bytes_processed_so_far_ += kPointerSize;
2085 2086 2087
}


2088
void Serializer::ObjectSerializer::VisitExternalReference(RelocInfo* rinfo) {
2089 2090 2091 2092
  int skip = OutputRawData(rinfo->target_address_address(),
                           kCanReturnSkipInsteadOfSkipping);
  HowToCode how_to_code = rinfo->IsCodedSpecially() ? kFromCode : kPlain;
  sink_->Put(kExternalReference + how_to_code + kStartOfObject, "ExternalRef");
2093
  sink_->PutInt(skip, "SkipB4ExternalRef");
2094
  Address target = rinfo->target_external_reference();
2095
  sink_->PutInt(serializer_->EncodeExternalReference(target), "reference id");
2096 2097 2098 2099
  bytes_processed_so_far_ += rinfo->target_address_size();
}


2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
void Serializer::ObjectSerializer::VisitInternalReference(RelocInfo* rinfo) {
  // We can only reference to internal references of code that has been output.
  DCHECK(is_code_object_ && code_has_been_output_);
  // We do not use skip from last patched pc to find the pc to patch, since
  // target_address_address may not return addresses in ascending order when
  // used for internal references. External references may be stored at the
  // end of the code in the constant pool, whereas internal references are
  // inline. That would cause the skip to be negative. Instead, we store the
  // offset from code entry.
  Address entry = Code::cast(object_)->entry();
  intptr_t pc_offset = rinfo->target_internal_reference_address() - entry;
  intptr_t target_offset = rinfo->target_internal_reference() - entry;
  DCHECK(0 <= pc_offset &&
         pc_offset <= Code::cast(object_)->instruction_size());
  DCHECK(0 <= target_offset &&
         target_offset <= Code::cast(object_)->instruction_size());
2116 2117 2118 2119
  sink_->Put(rinfo->rmode() == RelocInfo::INTERNAL_REFERENCE
                 ? kInternalReference
                 : kInternalReferenceEncoded,
             "InternalRef");
2120 2121 2122 2123 2124
  sink_->PutInt(static_cast<uintptr_t>(pc_offset), "internal ref address");
  sink_->PutInt(static_cast<uintptr_t>(target_offset), "internal ref value");
}


2125
void Serializer::ObjectSerializer::VisitRuntimeEntry(RelocInfo* rinfo) {
2126 2127 2128 2129
  int skip = OutputRawData(rinfo->target_address_address(),
                           kCanReturnSkipInsteadOfSkipping);
  HowToCode how_to_code = rinfo->IsCodedSpecially() ? kFromCode : kPlain;
  sink_->Put(kExternalReference + how_to_code + kStartOfObject, "ExternalRef");
2130
  sink_->PutInt(skip, "SkipB4ExternalRef");
2131 2132
  Address target = rinfo->target_address();
  sink_->PutInt(serializer_->EncodeExternalReference(target), "reference id");
2133
  bytes_processed_so_far_ += rinfo->target_address_size();
2134 2135 2136
}


2137
void Serializer::ObjectSerializer::VisitCodeTarget(RelocInfo* rinfo) {
2138 2139 2140 2141
  int skip = OutputRawData(rinfo->target_address_address(),
                           kCanReturnSkipInsteadOfSkipping);
  Code* object = Code::GetCodeFromTargetAddress(rinfo->target_address());
  serializer_->SerializeObject(object, kFromCode, kInnerPointer, skip);
2142
  bytes_processed_so_far_ += rinfo->target_address_size();
2143 2144 2145
}


2146
void Serializer::ObjectSerializer::VisitCodeEntry(Address entry_address) {
2147
  int skip = OutputRawData(entry_address, kCanReturnSkipInsteadOfSkipping);
2148 2149
  Code* object = Code::cast(Code::GetObjectFromEntryAddress(entry_address));
  serializer_->SerializeObject(object, kPlain, kInnerPointer, skip);
2150 2151 2152 2153
  bytes_processed_so_far_ += kPointerSize;
}


2154
void Serializer::ObjectSerializer::VisitCell(RelocInfo* rinfo) {
2155
  int skip = OutputRawData(rinfo->pc(), kCanReturnSkipInsteadOfSkipping);
2156 2157
  Cell* object = Cell::cast(rinfo->target_cell());
  serializer_->SerializeObject(object, kPlain, kInnerPointer, skip);
2158
  bytes_processed_so_far_ += kPointerSize;
2159 2160 2161
}


2162 2163 2164 2165 2166 2167
bool Serializer::ObjectSerializer::SerializeExternalNativeSourceString(
    int builtin_count,
    v8::String::ExternalOneByteStringResource** resource_pointer,
    FixedArray* source_cache, int resource_index) {
  for (int i = 0; i < builtin_count; i++) {
    Object* source = source_cache->get(i);
2168
    if (!source->IsUndefined()) {
2169 2170
      ExternalOneByteString* string = ExternalOneByteString::cast(source);
      typedef v8::String::ExternalOneByteStringResource Resource;
2171
      const Resource* resource = string->resource();
2172
      if (resource == *resource_pointer) {
2173
        sink_->Put(resource_index, "NativesStringResource");
2174 2175
        sink_->PutSection(i, "NativesStringResourceEnd");
        bytes_processed_so_far_ += sizeof(resource);
2176
        return true;
2177 2178 2179
      }
    }
  }
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
  return false;
}


void Serializer::ObjectSerializer::VisitExternalOneByteString(
    v8::String::ExternalOneByteStringResource** resource_pointer) {
  Address references_start = reinterpret_cast<Address>(resource_pointer);
  OutputRawData(references_start);
  if (SerializeExternalNativeSourceString(
          Natives::GetBuiltinsCount(), resource_pointer,
          serializer_->isolate()->heap()->natives_source_cache(),
          kNativesStringResource)) {
    return;
  }
  if (SerializeExternalNativeSourceString(
          CodeStubNatives::GetBuiltinsCount(), resource_pointer,
          serializer_->isolate()->heap()->code_stub_natives_source_cache(),
          kCodeStubNativesStringResource)) {
    return;
  }
2200
  // One of the strings in the natives cache should match the resource.  We
2201
  // don't expect any other kinds of external strings here.
2202 2203 2204 2205
  UNREACHABLE();
}


2206 2207 2208
Address Serializer::ObjectSerializer::PrepareCode() {
  // To make snapshots reproducible, we make a copy of the code object
  // and wipe all pointers in the copy, which we then serialize.
2209 2210
  Code* original = Code::cast(object_);
  Code* code = serializer_->CopyCode(original);
2211 2212
  // Code age headers are not serializable.
  code->MakeYoung(serializer_->isolate());
2213 2214 2215 2216
  int mode_mask = RelocInfo::kCodeTargetMask |
                  RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT) |
                  RelocInfo::ModeMask(RelocInfo::EXTERNAL_REFERENCE) |
                  RelocInfo::ModeMask(RelocInfo::RUNTIME_ENTRY) |
2217 2218
                  RelocInfo::ModeMask(RelocInfo::INTERNAL_REFERENCE) |
                  RelocInfo::ModeMask(RelocInfo::INTERNAL_REFERENCE_ENCODED);
2219
  for (RelocIterator it(code, mode_mask); !it.done(); it.next()) {
2220
    RelocInfo* rinfo = it.rinfo();
2221
    rinfo->WipeOut();
2222
  }
2223 2224 2225 2226
  // We need to wipe out the header fields *after* wiping out the
  // relocations, because some of these fields are needed for the latter.
  code->WipeOutHeader();
  return code->address();
2227 2228 2229
}


2230 2231
int Serializer::ObjectSerializer::OutputRawData(
    Address up_to, Serializer::ObjectSerializer::ReturnSkip return_skip) {
2232
  Address object_start = object_->address();
2233
  int base = bytes_processed_so_far_;
2234
  int up_to_offset = static_cast<int>(up_to - object_start);
2235 2236
  int to_skip = up_to_offset - bytes_processed_so_far_;
  int bytes_to_output = to_skip;
2237
  bytes_processed_so_far_ += to_skip;
2238 2239
  // 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.
2240
  DCHECK(to_skip >= 0);
2241
  bool outputting_code = false;
2242
  if (to_skip != 0 && is_code_object_ && !code_has_been_output_) {
2243 2244 2245 2246 2247
    // Output the code all at once and fix later.
    bytes_to_output = object_->Size() + to_skip - bytes_processed_so_far_;
    outputting_code = true;
    code_has_been_output_ = true;
  }
2248
  if (bytes_to_output != 0 && (!is_code_object_ || outputting_code)) {
yangguo's avatar
yangguo committed
2249 2250 2251 2252 2253 2254 2255
    if (!outputting_code && bytes_to_output == to_skip &&
        IsAligned(bytes_to_output, kPointerAlignment) &&
        bytes_to_output <= kNumberOfFixedRawData * kPointerSize) {
      int size_in_words = bytes_to_output >> kPointerSizeLog2;
      sink_->PutSection(kFixedRawDataStart + size_in_words, "FixedRawData");
      to_skip = 0;  // This instruction includes skip.
    } else {
2256
      // We always end up here if we are outputting the code of a code object.
yangguo's avatar
yangguo committed
2257
      sink_->Put(kVariableRawData, "VariableRawData");
2258
      sink_->PutInt(bytes_to_output, "length");
2259
    }
2260

2261
    if (is_code_object_) object_start = PrepareCode();
2262

2263
    const char* description = is_code_object_ ? "Code" : "Byte";
2264
    sink_->PutRaw(object_start + base, bytes_to_output, description);
2265
  }
2266 2267 2268 2269
  if (to_skip != 0 && return_skip == kIgnoringReturn) {
    sink_->Put(kSkip, "Skip");
    sink_->PutInt(to_skip, "SkipDistance");
    to_skip = 0;
2270
  }
2271
  return to_skip;
2272 2273 2274
}


2275
BackReference Serializer::AllocateLargeObject(int size) {
2276 2277
  // Large objects are allocated one-by-one when deserializing. We do not
  // have to keep track of multiple chunks.
2278
  large_objects_total_size_ += size;
2279
  return BackReference::LargeObjectReference(seen_large_objects_index_++);
2280 2281 2282
}


2283
BackReference Serializer::Allocate(AllocationSpace space, int size) {
2284
  DCHECK(space >= 0 && space < kNumberOfPreallocatedSpaces);
2285
  DCHECK(size > 0 && size <= static_cast<int>(max_chunk_size(space)));
2286
  uint32_t new_chunk_size = pending_chunk_[space] + size;
2287
  if (new_chunk_size > max_chunk_size(space)) {
2288 2289
    // The new chunk size would not fit onto a single page. Complete the
    // current chunk and start a new one.
2290 2291
    sink_->Put(kNextChunk, "NextChunk");
    sink_->Put(space, "NextChunkSpace");
2292
    completed_chunks_[space].Add(pending_chunk_[space]);
2293
    DCHECK_LE(completed_chunks_[space].length(), BackReference::kMaxChunkIndex);
2294 2295 2296
    pending_chunk_[space] = 0;
    new_chunk_size = size;
  }
2297
  uint32_t offset = pending_chunk_[space];
2298
  pending_chunk_[space] = new_chunk_size;
2299 2300
  return BackReference::Reference(space, completed_chunks_[space].length(),
                                  offset);
2301 2302 2303
}


2304 2305 2306
void Serializer::Pad() {
  // The non-branching GetInt will read up to 3 bytes too far, so we need
  // to pad the snapshot to make sure we don't read over the end.
2307 2308 2309
  for (unsigned i = 0; i < sizeof(int32_t) - 1; i++) {
    sink_->Put(kNop, "Padding");
  }
2310 2311 2312 2313
  // Pad up to pointer size for checksum.
  while (!IsAligned(sink_->Position(), kPointerAlignment)) {
    sink_->Put(kNop, "Padding");
  }
2314 2315 2316
}


2317 2318 2319 2320 2321 2322
void Serializer::InitializeCodeAddressMap() {
  isolate_->InitializeLoggingAndCounters();
  code_address_map_ = new CodeAddressMap(isolate_);
}


2323 2324 2325 2326 2327 2328 2329 2330
Code* Serializer::CopyCode(Code* code) {
  code_buffer_.Rewind(0);  // Clear buffer without deleting backing store.
  int size = code->CodeSize();
  code_buffer_.AddAll(Vector<byte>(code->address(), size));
  return Code::cast(HeapObject::FromAddress(&code_buffer_.first()));
}


2331 2332 2333
ScriptData* CodeSerializer::Serialize(Isolate* isolate,
                                      Handle<SharedFunctionInfo> info,
                                      Handle<String> source) {
2334 2335
  base::ElapsedTimer timer;
  if (FLAG_profile_deserialization) timer.Start();
2336
  if (FLAG_trace_serializer) {
2337 2338 2339 2340 2341
    PrintF("[Serializing from");
    Object* script = info->script();
    if (script->IsScript()) Script::cast(script)->name()->ShortPrint();
    PrintF("]\n");
  }
2342

2343
  // Serialize code object.
2344 2345
  SnapshotByteSink sink(info->code()->CodeSize() * 2);
  CodeSerializer cs(isolate, &sink, *source, info->code());
2346
  DisallowHeapAllocation no_gc;
2347
  Object** location = Handle<Object>::cast(info).location();
2348
  cs.VisitPointer(location);
2349
  cs.SerializeDeferredObjects();
2350
  cs.Pad();
2351

2352
  SerializedCodeData data(sink.data(), cs);
2353 2354 2355 2356 2357 2358 2359 2360 2361
  ScriptData* script_data = data.GetScriptData();

  if (FLAG_profile_deserialization) {
    double ms = timer.Elapsed().InMillisecondsF();
    int length = script_data->length();
    PrintF("[Serializing to %d bytes took %0.3f ms]\n", length, ms);
  }

  return script_data;
2362 2363 2364
}


2365
void CodeSerializer::SerializeObject(HeapObject* obj, HowToCode how_to_code,
2366
                                     WhereToPoint where_to_point, int skip) {
2367 2368 2369
  int root_index = root_index_map_.Lookup(obj);
  if (root_index != RootIndexMap::kInvalidRootIndex) {
    PutRoot(root_index, obj, how_to_code, where_to_point, skip);
2370 2371 2372
    return;
  }

2373
  if (SerializeKnownObject(obj, how_to_code, where_to_point, skip)) return;
2374

2375
  FlushSkip(skip);
2376

2377 2378
  if (obj->IsCode()) {
    Code* code_object = Code::cast(obj);
2379 2380 2381 2382 2383 2384 2385
    switch (code_object->kind()) {
      case Code::OPTIMIZED_FUNCTION:  // No optimized code compiled yet.
      case Code::HANDLER:             // No handlers patched in yet.
      case Code::REGEXP:              // No regexp literals initialized yet.
      case Code::NUMBER_OF_KINDS:     // Pseudo enum value.
        CHECK(false);
      case Code::BUILTIN:
2386 2387
        SerializeBuiltin(code_object->builtin_index(), how_to_code,
                         where_to_point);
2388 2389
        return;
      case Code::STUB:
2390
        SerializeCodeStub(code_object->stub_key(), how_to_code, where_to_point);
2391 2392 2393 2394
        return;
#define IC_KIND_CASE(KIND) case Code::KIND:
        IC_KIND_LIST(IC_KIND_CASE)
#undef IC_KIND_CASE
2395
        SerializeIC(code_object, how_to_code, where_to_point);
2396
        return;
2397
      case Code::FUNCTION:
2398 2399 2400
        DCHECK(code_object->has_reloc_info_for_serialization());
        // Only serialize the code for the toplevel function unless specified
        // by flag. Replace code of inner functions by the lazy compile builtin.
2401
        // This is safe, as checked in Compiler::GetSharedFunctionInfo.
2402
        if (code_object != main_code_ && !FLAG_serialize_inner) {
2403
          SerializeBuiltin(Builtins::kCompileLazy, how_to_code, where_to_point);
2404
        } else {
2405
          SerializeGeneric(code_object, how_to_code, where_to_point);
2406
        }
2407
        return;
2408
    }
2409
    UNREACHABLE();
2410 2411
  }

2412
  // Past this point we should not see any (context-specific) maps anymore.
2413
  CHECK(!obj->IsMap());
2414
  // There should be no references to the global object embedded.
2415
  CHECK(!obj->IsJSGlobalProxy() && !obj->IsGlobalObject());
2416
  // There should be no hash table embedded. They would require rehashing.
2417
  CHECK(!obj->IsHashTable());
2418 2419
  // We expect no instantiated function objects or contexts.
  CHECK(!obj->IsJSFunction() && !obj->IsContext());
2420

2421
  SerializeGeneric(obj, how_to_code, where_to_point);
2422 2423 2424
}


2425 2426 2427
void CodeSerializer::SerializeGeneric(HeapObject* heap_object,
                                      HowToCode how_to_code,
                                      WhereToPoint where_to_point) {
2428 2429 2430 2431 2432 2433 2434
  // Object has not yet been serialized.  Serialize it here.
  ObjectSerializer serializer(this, heap_object, sink_, how_to_code,
                              where_to_point);
  serializer.Serialize();
}


2435
void CodeSerializer::SerializeBuiltin(int builtin_index, HowToCode how_to_code,
2436
                                      WhereToPoint where_to_point) {
2437
  DCHECK((how_to_code == kPlain && where_to_point == kStartOfObject) ||
2438
         (how_to_code == kPlain && where_to_point == kInnerPointer) ||
2439
         (how_to_code == kFromCode && where_to_point == kInnerPointer));
2440 2441
  DCHECK_LT(builtin_index, Builtins::builtin_count);
  DCHECK_LE(0, builtin_index);
2442

2443
  if (FLAG_trace_serializer) {
2444
    PrintF(" Encoding builtin: %s\n",
2445 2446 2447
           isolate()->builtins()->name(builtin_index));
  }

2448
  sink_->Put(kBuiltin + how_to_code + where_to_point, "Builtin");
2449
  sink_->PutInt(builtin_index, "builtin_index");
2450 2451 2452
}


2453
void CodeSerializer::SerializeCodeStub(uint32_t stub_key, HowToCode how_to_code,
2454
                                       WhereToPoint where_to_point) {
2455 2456 2457
  DCHECK((how_to_code == kPlain && where_to_point == kStartOfObject) ||
         (how_to_code == kPlain && where_to_point == kInnerPointer) ||
         (how_to_code == kFromCode && where_to_point == kInnerPointer));
2458
  DCHECK(CodeStub::MajorKeyFromKey(stub_key) != CodeStub::NoCache);
2459
  DCHECK(!CodeStub::GetCode(isolate(), stub_key).is_null());
2460 2461 2462

  int index = AddCodeStubKey(stub_key) + kCodeStubsBaseIndex;

2463
  if (FLAG_trace_serializer) {
2464
    PrintF(" Encoding code stub %s as %d\n",
2465 2466 2467 2468 2469 2470 2471 2472 2473
           CodeStub::MajorName(CodeStub::MajorKeyFromKey(stub_key), false),
           index);
  }

  sink_->Put(kAttachedReference + how_to_code + where_to_point, "CodeStub");
  sink_->PutInt(index, "CodeStub key");
}


2474 2475 2476 2477 2478
void CodeSerializer::SerializeIC(Code* ic, HowToCode how_to_code,
                                 WhereToPoint where_to_point) {
  // The IC may be implemented as a stub.
  uint32_t stub_key = ic->stub_key();
  if (stub_key != CodeStub::NoCacheKey()) {
2479
    if (FLAG_trace_serializer) {
2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
      PrintF(" %s is a code stub\n", Code::Kind2String(ic->kind()));
    }
    SerializeCodeStub(stub_key, how_to_code, where_to_point);
    return;
  }
  // The IC may be implemented as builtin. Only real builtins have an
  // actual builtin_index value attached (otherwise it's just garbage).
  // Compare to make sure we are really dealing with a builtin.
  int builtin_index = ic->builtin_index();
  if (builtin_index < Builtins::builtin_count) {
    Builtins::Name name = static_cast<Builtins::Name>(builtin_index);
    Code* builtin = isolate()->builtins()->builtin(name);
    if (builtin == ic) {
2493
      if (FLAG_trace_serializer) {
2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
        PrintF(" %s is a builtin\n", Code::Kind2String(ic->kind()));
      }
      DCHECK(ic->kind() == Code::KEYED_LOAD_IC ||
             ic->kind() == Code::KEYED_STORE_IC);
      SerializeBuiltin(builtin_index, how_to_code, where_to_point);
      return;
    }
  }
  // The IC may also just be a piece of code kept in the non_monomorphic_cache.
  // In that case, just serialize as a normal code object.
2504
  if (FLAG_trace_serializer) {
2505 2506 2507
    PrintF(" %s has no special handling\n", Code::Kind2String(ic->kind()));
  }
  DCHECK(ic->kind() == Code::LOAD_IC || ic->kind() == Code::STORE_IC);
2508
  SerializeGeneric(ic, how_to_code, where_to_point);
2509 2510 2511
}


2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523
int CodeSerializer::AddCodeStubKey(uint32_t stub_key) {
  // TODO(yangguo) Maybe we need a hash table for a faster lookup than O(n^2).
  int index = 0;
  while (index < stub_keys_.length()) {
    if (stub_keys_[index] == stub_key) return index;
    index++;
  }
  stub_keys_.Add(stub_key);
  return index;
}


2524
MaybeHandle<SharedFunctionInfo> CodeSerializer::Deserialize(
2525
    Isolate* isolate, ScriptData* cached_data, Handle<String> source) {
2526 2527
  base::ElapsedTimer timer;
  if (FLAG_profile_deserialization) timer.Start();
2528

2529
  HandleScope scope(isolate);
2530

rmcilroy's avatar
rmcilroy committed
2531
  base::SmartPointer<SerializedCodeData> scd(
2532
      SerializedCodeData::FromCachedData(isolate, cached_data, *source));
2533 2534 2535 2536 2537
  if (scd.is_empty()) {
    if (FLAG_profile_deserialization) PrintF("[Cached code failed check]\n");
    DCHECK(cached_data->rejected());
    return MaybeHandle<SharedFunctionInfo>();
  }
2538

2539 2540 2541 2542 2543 2544 2545 2546 2547
  // Prepare and register list of attached objects.
  Vector<const uint32_t> code_stub_keys = scd->CodeStubKeys();
  Vector<Handle<Object> > attached_objects = Vector<Handle<Object> >::New(
      code_stub_keys.length() + kCodeStubsBaseIndex);
  attached_objects[kSourceObjectIndex] = source;
  for (int i = 0; i < code_stub_keys.length(); i++) {
    attached_objects[i + kCodeStubsBaseIndex] =
        CodeStub::GetCode(isolate, code_stub_keys[i]).ToHandleChecked();
  }
2548

2549
  Deserializer deserializer(scd.get());
2550
  deserializer.SetAttachedObjects(attached_objects);
2551

2552 2553 2554 2555 2556 2557
  // Deserialize.
  Handle<SharedFunctionInfo> result;
  if (!deserializer.DeserializeCode(isolate).ToHandle(&result)) {
    // Deserializing may fail if the reservations cannot be fulfilled.
    if (FLAG_profile_deserialization) PrintF("[Deserializing failed]\n");
    return MaybeHandle<SharedFunctionInfo>();
2558
  }
2559
  deserializer.FlushICacheForNewCodeObjects();
2560

2561 2562
  if (FLAG_profile_deserialization) {
    double ms = timer.Elapsed().InMillisecondsF();
2563
    int length = cached_data->length();
2564 2565
    PrintF("[Deserializing from %d bytes took %0.3f ms]\n", length, ms);
  }
2566
  result->set_deserialized(true);
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577

  if (isolate->logger()->is_logging_code_events() ||
      isolate->cpu_profiler()->is_profiling()) {
    String* name = isolate->heap()->empty_string();
    if (result->script()->IsScript()) {
      Script* script = Script::cast(result->script());
      if (script->name()->IsString()) name = String::cast(script->name());
    }
    isolate->logger()->CodeCreateEvent(Logger::SCRIPT_TAG, result->code(),
                                       *result, NULL, name);
  }
2578
  return scope.CloseAndEscape(result);
2579
}
2580 2581


2582 2583 2584 2585 2586 2587 2588 2589 2590
void SerializedData::AllocateData(int size) {
  DCHECK(!owns_data_);
  data_ = NewArray<byte>(size);
  size_ = size;
  owns_data_ = true;
  DCHECK(IsAligned(reinterpret_cast<intptr_t>(data_), kPointerAlignment));
}


2591
SnapshotData::SnapshotData(const Serializer& ser) {
2592 2593 2594
  DisallowHeapAllocation no_gc;
  List<Reservation> reservations;
  ser.EncodeReservations(&reservations);
2595
  const List<byte>& payload = ser.sink()->data();
2596 2597 2598 2599 2600 2601 2602 2603 2604

  // Calculate sizes.
  int reservation_size = reservations.length() * kInt32Size;
  int size = kHeaderSize + reservation_size + payload.length();

  // Allocate backing store and create result data.
  AllocateData(size);

  // Set header values.
2605
  SetMagicNumber(ser.isolate());
2606
  SetHeaderValue(kCheckSumOffset, Version::Hash());
2607
  SetHeaderValue(kNumReservationsOffset, reservations.length());
2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
  SetHeaderValue(kPayloadLengthOffset, payload.length());

  // Copy reservation chunk sizes.
  CopyBytes(data_ + kHeaderSize, reinterpret_cast<byte*>(reservations.begin()),
            reservation_size);

  // Copy serialized data.
  CopyBytes(data_ + kHeaderSize + reservation_size, payload.begin(),
            static_cast<size_t>(payload.length()));
}


bool SnapshotData::IsSane() {
  return GetHeaderValue(kCheckSumOffset) == Version::Hash();
}


Vector<const SerializedData::Reservation> SnapshotData::Reservations() const {
  return Vector<const Reservation>(
      reinterpret_cast<const Reservation*>(data_ + kHeaderSize),
2628
      GetHeaderValue(kNumReservationsOffset));
2629 2630 2631 2632
}


Vector<const byte> SnapshotData::Payload() const {
2633
  int reservations_size = GetHeaderValue(kNumReservationsOffset) * kInt32Size;
2634 2635 2636 2637 2638 2639 2640
  const byte* payload = data_ + kHeaderSize + reservations_size;
  int length = GetHeaderValue(kPayloadLengthOffset);
  DCHECK_EQ(data_ + size_, payload + length);
  return Vector<const byte>(payload, length);
}


2641 2642 2643
class Checksum {
 public:
  explicit Checksum(Vector<const byte> payload) {
2644 2645 2646 2647 2648
#ifdef MEMORY_SANITIZER
    // Computing the checksum includes padding bytes for objects like strings.
    // Mark every object as initialized in the code serializer.
    MSAN_MEMORY_IS_INITIALIZED(payload.start(), payload.length());
#endif  // MEMORY_SANITIZER
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680
    // Fletcher's checksum. Modified to reduce 64-bit sums to 32-bit.
    uintptr_t a = 1;
    uintptr_t b = 0;
    const uintptr_t* cur = reinterpret_cast<const uintptr_t*>(payload.start());
    DCHECK(IsAligned(payload.length(), kIntptrSize));
    const uintptr_t* end = cur + payload.length() / kIntptrSize;
    while (cur < end) {
      // Unsigned overflow expected and intended.
      a += *cur++;
      b += a;
    }
#if V8_HOST_ARCH_64_BIT
    a ^= a >> 32;
    b ^= b >> 32;
#endif  // V8_HOST_ARCH_64_BIT
    a_ = static_cast<uint32_t>(a);
    b_ = static_cast<uint32_t>(b);
  }

  bool Check(uint32_t a, uint32_t b) const { return a == a_ && b == b_; }

  uint32_t a() const { return a_; }
  uint32_t b() const { return b_; }

 private:
  uint32_t a_;
  uint32_t b_;

  DISALLOW_COPY_AND_ASSIGN(Checksum);
};


2681
SerializedCodeData::SerializedCodeData(const List<byte>& payload,
2682
                                       const CodeSerializer& cs) {
2683
  DisallowHeapAllocation no_gc;
2684
  const List<uint32_t>* stub_keys = cs.stub_keys();
2685

2686 2687
  List<Reservation> reservations;
  cs.EncodeReservations(&reservations);
2688

2689
  // Calculate sizes.
2690
  int reservation_size = reservations.length() * kInt32Size;
2691 2692
  int num_stub_keys = stub_keys->length();
  int stub_keys_size = stub_keys->length() * kInt32Size;
2693 2694 2695
  int payload_offset = kHeaderSize + reservation_size + stub_keys_size;
  int padded_payload_offset = POINTER_SIZE_ALIGN(payload_offset);
  int size = padded_payload_offset + payload.length();
2696 2697

  // Allocate backing store and create result data.
2698
  AllocateData(size);
2699 2700

  // Set header values.
2701
  SetMagicNumber(cs.isolate());
2702 2703 2704 2705 2706
  SetHeaderValue(kVersionHashOffset, Version::Hash());
  SetHeaderValue(kSourceHashOffset, SourceHash(cs.source()));
  SetHeaderValue(kCpuFeaturesOffset,
                 static_cast<uint32_t>(CpuFeatures::SupportedFeatures()));
  SetHeaderValue(kFlagHashOffset, FlagList::Hash());
2707
  SetHeaderValue(kNumReservationsOffset, reservations.length());
2708
  SetHeaderValue(kNumCodeStubKeysOffset, num_stub_keys);
2709
  SetHeaderValue(kPayloadLengthOffset, payload.length());
2710

2711 2712 2713 2714
  Checksum checksum(payload.ToConstVector());
  SetHeaderValue(kChecksum1Offset, checksum.a());
  SetHeaderValue(kChecksum2Offset, checksum.b());

2715
  // Copy reservation chunk sizes.
2716
  CopyBytes(data_ + kHeaderSize, reinterpret_cast<byte*>(reservations.begin()),
2717
            reservation_size);
2718 2719

  // Copy code stub keys.
2720
  CopyBytes(data_ + kHeaderSize + reservation_size,
2721
            reinterpret_cast<byte*>(stub_keys->begin()), stub_keys_size);
2722

2723 2724
  memset(data_ + payload_offset, 0, padded_payload_offset - payload_offset);

2725
  // Copy serialized data.
2726 2727
  CopyBytes(data_ + padded_payload_offset, payload.begin(),
            static_cast<size_t>(payload.length()));
2728 2729 2730
}


2731
SerializedCodeData::SanityCheckResult SerializedCodeData::SanityCheck(
2732 2733
    Isolate* isolate, String* source) const {
  uint32_t magic_number = GetMagicNumber();
2734
  if (magic_number != ComputeMagicNumber(isolate)) return MAGIC_NUMBER_MISMATCH;
2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748
  uint32_t version_hash = GetHeaderValue(kVersionHashOffset);
  uint32_t source_hash = GetHeaderValue(kSourceHashOffset);
  uint32_t cpu_features = GetHeaderValue(kCpuFeaturesOffset);
  uint32_t flags_hash = GetHeaderValue(kFlagHashOffset);
  uint32_t c1 = GetHeaderValue(kChecksum1Offset);
  uint32_t c2 = GetHeaderValue(kChecksum2Offset);
  if (version_hash != Version::Hash()) return VERSION_MISMATCH;
  if (source_hash != SourceHash(source)) return SOURCE_MISMATCH;
  if (cpu_features != static_cast<uint32_t>(CpuFeatures::SupportedFeatures())) {
    return CPU_FEATURES_MISMATCH;
  }
  if (flags_hash != FlagList::Hash()) return FLAGS_MISMATCH;
  if (!Checksum(Payload()).Check(c1, c2)) return CHECKSUM_MISMATCH;
  return CHECK_SUCCESS;
2749
}
2750 2751


2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766
// Return ScriptData object and relinquish ownership over it to the caller.
ScriptData* SerializedCodeData::GetScriptData() {
  DCHECK(owns_data_);
  ScriptData* result = new ScriptData(data_, size_);
  result->AcquireDataOwnership();
  owns_data_ = false;
  data_ = NULL;
  return result;
}


Vector<const SerializedData::Reservation> SerializedCodeData::Reservations()
    const {
  return Vector<const Reservation>(
      reinterpret_cast<const Reservation*>(data_ + kHeaderSize),
2767
      GetHeaderValue(kNumReservationsOffset));
2768 2769 2770 2771
}


Vector<const byte> SerializedCodeData::Payload() const {
2772
  int reservations_size = GetHeaderValue(kNumReservationsOffset) * kInt32Size;
2773
  int code_stubs_size = GetHeaderValue(kNumCodeStubKeysOffset) * kInt32Size;
2774 2775 2776 2777
  int payload_offset = kHeaderSize + reservations_size + code_stubs_size;
  int padded_payload_offset = POINTER_SIZE_ALIGN(payload_offset);
  const byte* payload = data_ + padded_payload_offset;
  DCHECK(IsAligned(reinterpret_cast<intptr_t>(payload), kPointerAlignment));
2778 2779 2780 2781 2782 2783 2784
  int length = GetHeaderValue(kPayloadLengthOffset);
  DCHECK_EQ(data_ + size_, payload + length);
  return Vector<const byte>(payload, length);
}


Vector<const uint32_t> SerializedCodeData::CodeStubKeys() const {
2785
  int reservations_size = GetHeaderValue(kNumReservationsOffset) * kInt32Size;
2786 2787 2788 2789
  const byte* start = data_ + kHeaderSize + reservations_size;
  return Vector<const uint32_t>(reinterpret_cast<const uint32_t*>(start),
                                GetHeaderValue(kNumCodeStubKeysOffset));
}
2790 2791 2792 2793 2794 2795


SerializedCodeData::SerializedCodeData(ScriptData* data)
    : SerializedData(const_cast<byte*>(data->data()), data->length()) {}


2796 2797
SerializedCodeData* SerializedCodeData::FromCachedData(Isolate* isolate,
                                                       ScriptData* cached_data,
2798 2799 2800
                                                       String* source) {
  DisallowHeapAllocation no_gc;
  SerializedCodeData* scd = new SerializedCodeData(cached_data);
2801
  SanityCheckResult r = scd->SanityCheck(isolate, source);
2802
  if (r == CHECK_SUCCESS) return scd;
2803
  cached_data->Reject();
2804
  source->GetIsolate()->counters()->code_cache_reject_reason()->AddSample(r);
2805 2806 2807
  delete scd;
  return NULL;
}
2808 2809
}  // namespace internal
}  // namespace v8