Home | History | Annotate | Download | only in snapshot
      1 // Copyright 2012 the V8 project authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include "src/snapshot/serialize.h"
      6 
      7 #include "src/accessors.h"
      8 #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/deoptimizer.h"
     13 #include "src/execution.h"
     14 #include "src/global-handles.h"
     15 #include "src/ic/ic.h"
     16 #include "src/ic/stub-cache.h"
     17 #include "src/objects.h"
     18 #include "src/parsing/parser.h"
     19 #include "src/profiler/cpu-profiler.h"
     20 #include "src/runtime/runtime.h"
     21 #include "src/snapshot/natives.h"
     22 #include "src/snapshot/snapshot.h"
     23 #include "src/snapshot/snapshot-source-sink.h"
     24 #include "src/v8.h"
     25 #include "src/v8threads.h"
     26 #include "src/version.h"
     27 
     28 namespace v8 {
     29 namespace internal {
     30 
     31 
     32 // -----------------------------------------------------------------------------
     33 // Coding of external references.
     34 
     35 
     36 ExternalReferenceTable* ExternalReferenceTable::instance(Isolate* isolate) {
     37   ExternalReferenceTable* external_reference_table =
     38       isolate->external_reference_table();
     39   if (external_reference_table == NULL) {
     40     external_reference_table = new ExternalReferenceTable(isolate);
     41     isolate->set_external_reference_table(external_reference_table);
     42   }
     43   return external_reference_table;
     44 }
     45 
     46 
     47 ExternalReferenceTable::ExternalReferenceTable(Isolate* isolate) {
     48   // Miscellaneous
     49   Add(ExternalReference::roots_array_start(isolate).address(),
     50       "Heap::roots_array_start()");
     51   Add(ExternalReference::address_of_stack_limit(isolate).address(),
     52       "StackGuard::address_of_jslimit()");
     53   Add(ExternalReference::address_of_real_stack_limit(isolate).address(),
     54       "StackGuard::address_of_real_jslimit()");
     55   Add(ExternalReference::new_space_start(isolate).address(),
     56       "Heap::NewSpaceStart()");
     57   Add(ExternalReference::new_space_mask(isolate).address(),
     58       "Heap::NewSpaceMask()");
     59   Add(ExternalReference::new_space_allocation_limit_address(isolate).address(),
     60       "Heap::NewSpaceAllocationLimitAddress()");
     61   Add(ExternalReference::new_space_allocation_top_address(isolate).address(),
     62       "Heap::NewSpaceAllocationTopAddress()");
     63   Add(ExternalReference::mod_two_doubles_operation(isolate).address(),
     64       "mod_two_doubles");
     65   // Keyed lookup cache.
     66   Add(ExternalReference::keyed_lookup_cache_keys(isolate).address(),
     67       "KeyedLookupCache::keys()");
     68   Add(ExternalReference::keyed_lookup_cache_field_offsets(isolate).address(),
     69       "KeyedLookupCache::field_offsets()");
     70   Add(ExternalReference::handle_scope_next_address(isolate).address(),
     71       "HandleScope::next");
     72   Add(ExternalReference::handle_scope_limit_address(isolate).address(),
     73       "HandleScope::limit");
     74   Add(ExternalReference::handle_scope_level_address(isolate).address(),
     75       "HandleScope::level");
     76   Add(ExternalReference::new_deoptimizer_function(isolate).address(),
     77       "Deoptimizer::New()");
     78   Add(ExternalReference::compute_output_frames_function(isolate).address(),
     79       "Deoptimizer::ComputeOutputFrames()");
     80   Add(ExternalReference::address_of_min_int().address(),
     81       "LDoubleConstant::min_int");
     82   Add(ExternalReference::address_of_one_half().address(),
     83       "LDoubleConstant::one_half");
     84   Add(ExternalReference::isolate_address(isolate).address(), "isolate");
     85   Add(ExternalReference::address_of_negative_infinity().address(),
     86       "LDoubleConstant::negative_infinity");
     87   Add(ExternalReference::power_double_double_function(isolate).address(),
     88       "power_double_double_function");
     89   Add(ExternalReference::power_double_int_function(isolate).address(),
     90       "power_double_int_function");
     91   Add(ExternalReference::math_log_double_function(isolate).address(),
     92       "std::log");
     93   Add(ExternalReference::store_buffer_top(isolate).address(),
     94       "store_buffer_top");
     95   Add(ExternalReference::address_of_the_hole_nan().address(), "the_hole_nan");
     96   Add(ExternalReference::get_date_field_function(isolate).address(),
     97       "JSDate::GetField");
     98   Add(ExternalReference::date_cache_stamp(isolate).address(),
     99       "date_cache_stamp");
    100   Add(ExternalReference::address_of_pending_message_obj(isolate).address(),
    101       "address_of_pending_message_obj");
    102   Add(ExternalReference::get_make_code_young_function(isolate).address(),
    103       "Code::MakeCodeYoung");
    104   Add(ExternalReference::cpu_features().address(), "cpu_features");
    105   Add(ExternalReference::old_space_allocation_top_address(isolate).address(),
    106       "Heap::OldSpaceAllocationTopAddress");
    107   Add(ExternalReference::old_space_allocation_limit_address(isolate).address(),
    108       "Heap::OldSpaceAllocationLimitAddress");
    109   Add(ExternalReference::allocation_sites_list_address(isolate).address(),
    110       "Heap::allocation_sites_list_address()");
    111   Add(ExternalReference::address_of_uint32_bias().address(), "uint32_bias");
    112   Add(ExternalReference::get_mark_code_as_executed_function(isolate).address(),
    113       "Code::MarkCodeAsExecuted");
    114   Add(ExternalReference::is_profiling_address(isolate).address(),
    115       "CpuProfiler::is_profiling");
    116   Add(ExternalReference::scheduled_exception_address(isolate).address(),
    117       "Isolate::scheduled_exception");
    118   Add(ExternalReference::invoke_function_callback(isolate).address(),
    119       "InvokeFunctionCallback");
    120   Add(ExternalReference::invoke_accessor_getter_callback(isolate).address(),
    121       "InvokeAccessorGetterCallback");
    122   Add(ExternalReference::log_enter_external_function(isolate).address(),
    123       "Logger::EnterExternal");
    124   Add(ExternalReference::log_leave_external_function(isolate).address(),
    125       "Logger::LeaveExternal");
    126   Add(ExternalReference::address_of_minus_one_half().address(),
    127       "double_constants.minus_one_half");
    128   Add(ExternalReference::stress_deopt_count(isolate).address(),
    129       "Isolate::stress_deopt_count_address()");
    130   Add(ExternalReference::virtual_handler_register(isolate).address(),
    131       "Isolate::virtual_handler_register()");
    132   Add(ExternalReference::virtual_slot_register(isolate).address(),
    133       "Isolate::virtual_slot_register()");
    134   Add(ExternalReference::runtime_function_table_address(isolate).address(),
    135       "Runtime::runtime_function_table_address()");
    136 
    137   // Debug addresses
    138   Add(ExternalReference::debug_after_break_target_address(isolate).address(),
    139       "Debug::after_break_target_address()");
    140   Add(ExternalReference::debug_is_active_address(isolate).address(),
    141       "Debug::is_active_address()");
    142   Add(ExternalReference::debug_step_in_enabled_address(isolate).address(),
    143       "Debug::step_in_enabled_address()");
    144 
    145 #ifndef V8_INTERPRETED_REGEXP
    146   Add(ExternalReference::re_case_insensitive_compare_uc16(isolate).address(),
    147       "NativeRegExpMacroAssembler::CaseInsensitiveCompareUC16()");
    148   Add(ExternalReference::re_check_stack_guard_state(isolate).address(),
    149       "RegExpMacroAssembler*::CheckStackGuardState()");
    150   Add(ExternalReference::re_grow_stack(isolate).address(),
    151       "NativeRegExpMacroAssembler::GrowStack()");
    152   Add(ExternalReference::re_word_character_map().address(),
    153       "NativeRegExpMacroAssembler::word_character_map");
    154   Add(ExternalReference::address_of_regexp_stack_limit(isolate).address(),
    155       "RegExpStack::limit_address()");
    156   Add(ExternalReference::address_of_regexp_stack_memory_address(isolate)
    157           .address(),
    158       "RegExpStack::memory_address()");
    159   Add(ExternalReference::address_of_regexp_stack_memory_size(isolate).address(),
    160       "RegExpStack::memory_size()");
    161   Add(ExternalReference::address_of_static_offsets_vector(isolate).address(),
    162       "OffsetsVector::static_offsets_vector");
    163 #endif  // V8_INTERPRETED_REGEXP
    164 
    165   // The following populates all of the different type of external references
    166   // into the ExternalReferenceTable.
    167   //
    168   // NOTE: This function was originally 100k of code.  It has since been
    169   // rewritten to be mostly table driven, as the callback macro style tends to
    170   // very easily cause code bloat.  Please be careful in the future when adding
    171   // new references.
    172 
    173   struct RefTableEntry {
    174     uint16_t id;
    175     const char* name;
    176   };
    177 
    178   static const RefTableEntry c_builtins[] = {
    179 #define DEF_ENTRY_C(name, ignored)           \
    180   { Builtins::c_##name, "Builtins::" #name } \
    181   ,
    182       BUILTIN_LIST_C(DEF_ENTRY_C)
    183 #undef DEF_ENTRY_C
    184   };
    185 
    186   for (unsigned i = 0; i < arraysize(c_builtins); ++i) {
    187     ExternalReference ref(static_cast<Builtins::CFunctionId>(c_builtins[i].id),
    188                           isolate);
    189     Add(ref.address(), c_builtins[i].name);
    190   }
    191 
    192   static const RefTableEntry builtins[] = {
    193 #define DEF_ENTRY_C(name, ignored)          \
    194   { Builtins::k##name, "Builtins::" #name } \
    195   ,
    196 #define DEF_ENTRY_A(name, i1, i2, i3)       \
    197   { Builtins::k##name, "Builtins::" #name } \
    198   ,
    199       BUILTIN_LIST_C(DEF_ENTRY_C) BUILTIN_LIST_A(DEF_ENTRY_A)
    200           BUILTIN_LIST_DEBUG_A(DEF_ENTRY_A)
    201 #undef DEF_ENTRY_C
    202 #undef DEF_ENTRY_A
    203   };
    204 
    205   for (unsigned i = 0; i < arraysize(builtins); ++i) {
    206     ExternalReference ref(static_cast<Builtins::Name>(builtins[i].id), isolate);
    207     Add(ref.address(), builtins[i].name);
    208   }
    209 
    210   static const RefTableEntry runtime_functions[] = {
    211 #define RUNTIME_ENTRY(name, i1, i2)       \
    212   { Runtime::k##name, "Runtime::" #name } \
    213   ,
    214       FOR_EACH_INTRINSIC(RUNTIME_ENTRY)
    215 #undef RUNTIME_ENTRY
    216   };
    217 
    218   for (unsigned i = 0; i < arraysize(runtime_functions); ++i) {
    219     ExternalReference ref(
    220         static_cast<Runtime::FunctionId>(runtime_functions[i].id), isolate);
    221     Add(ref.address(), runtime_functions[i].name);
    222   }
    223 
    224   // Stat counters
    225   struct StatsRefTableEntry {
    226     StatsCounter* (Counters::*counter)();
    227     const char* name;
    228   };
    229 
    230   static const StatsRefTableEntry stats_ref_table[] = {
    231 #define COUNTER_ENTRY(name, caption)      \
    232   { &Counters::name, "Counters::" #name } \
    233   ,
    234       STATS_COUNTER_LIST_1(COUNTER_ENTRY) STATS_COUNTER_LIST_2(COUNTER_ENTRY)
    235 #undef COUNTER_ENTRY
    236   };
    237 
    238   Counters* counters = isolate->counters();
    239   for (unsigned i = 0; i < arraysize(stats_ref_table); ++i) {
    240     // To make sure the indices are not dependent on whether counters are
    241     // enabled, use a dummy address as filler.
    242     Address address = NotAvailable();
    243     StatsCounter* counter = (counters->*(stats_ref_table[i].counter))();
    244     if (counter->Enabled()) {
    245       address = reinterpret_cast<Address>(counter->GetInternalPointer());
    246     }
    247     Add(address, stats_ref_table[i].name);
    248   }
    249 
    250   // Top addresses
    251   static const char* address_names[] = {
    252 #define BUILD_NAME_LITERAL(Name, name) "Isolate::" #name "_address",
    253       FOR_EACH_ISOLATE_ADDRESS_NAME(BUILD_NAME_LITERAL) NULL
    254 #undef BUILD_NAME_LITERAL
    255   };
    256 
    257   for (int i = 0; i < Isolate::kIsolateAddressCount; ++i) {
    258     Add(isolate->get_address_from_id(static_cast<Isolate::AddressId>(i)),
    259         address_names[i]);
    260   }
    261 
    262   // Accessors
    263   struct AccessorRefTable {
    264     Address address;
    265     const char* name;
    266   };
    267 
    268   static const AccessorRefTable accessors[] = {
    269 #define ACCESSOR_INFO_DECLARATION(name)                                     \
    270   { FUNCTION_ADDR(&Accessors::name##Getter), "Accessors::" #name "Getter" } \
    271   , {FUNCTION_ADDR(&Accessors::name##Setter), "Accessors::" #name "Setter"},
    272       ACCESSOR_INFO_LIST(ACCESSOR_INFO_DECLARATION)
    273 #undef ACCESSOR_INFO_DECLARATION
    274   };
    275 
    276   for (unsigned i = 0; i < arraysize(accessors); ++i) {
    277     Add(accessors[i].address, accessors[i].name);
    278   }
    279 
    280   StubCache* stub_cache = isolate->stub_cache();
    281 
    282   // Stub cache tables
    283   Add(stub_cache->key_reference(StubCache::kPrimary).address(),
    284       "StubCache::primary_->key");
    285   Add(stub_cache->value_reference(StubCache::kPrimary).address(),
    286       "StubCache::primary_->value");
    287   Add(stub_cache->map_reference(StubCache::kPrimary).address(),
    288       "StubCache::primary_->map");
    289   Add(stub_cache->key_reference(StubCache::kSecondary).address(),
    290       "StubCache::secondary_->key");
    291   Add(stub_cache->value_reference(StubCache::kSecondary).address(),
    292       "StubCache::secondary_->value");
    293   Add(stub_cache->map_reference(StubCache::kSecondary).address(),
    294       "StubCache::secondary_->map");
    295 
    296   // Runtime entries
    297   Add(ExternalReference::delete_handle_scope_extensions(isolate).address(),
    298       "HandleScope::DeleteExtensions");
    299   Add(ExternalReference::incremental_marking_record_write_function(isolate)
    300           .address(),
    301       "IncrementalMarking::RecordWrite");
    302   Add(ExternalReference::store_buffer_overflow_function(isolate).address(),
    303       "StoreBuffer::StoreBufferOverflow");
    304 
    305   // Add a small set of deopt entry addresses to encoder without generating the
    306   // deopt table code, which isn't possible at deserialization time.
    307   HandleScope scope(isolate);
    308   for (int entry = 0; entry < kDeoptTableSerializeEntryCount; ++entry) {
    309     Address address = Deoptimizer::GetDeoptimizationEntry(
    310         isolate,
    311         entry,
    312         Deoptimizer::LAZY,
    313         Deoptimizer::CALCULATE_ENTRY_ADDRESS);
    314     Add(address, "lazy_deopt");
    315   }
    316 }
    317 
    318 
    319 ExternalReferenceEncoder::ExternalReferenceEncoder(Isolate* isolate) {
    320   map_ = isolate->external_reference_map();
    321   if (map_ != NULL) return;
    322   map_ = new HashMap(HashMap::PointersMatch);
    323   ExternalReferenceTable* table = ExternalReferenceTable::instance(isolate);
    324   for (int i = 0; i < table->size(); ++i) {
    325     Address addr = table->address(i);
    326     if (addr == ExternalReferenceTable::NotAvailable()) continue;
    327     // We expect no duplicate external references entries in the table.
    328     DCHECK_NULL(map_->Lookup(addr, Hash(addr)));
    329     map_->LookupOrInsert(addr, Hash(addr))->value = reinterpret_cast<void*>(i);
    330   }
    331   isolate->set_external_reference_map(map_);
    332 }
    333 
    334 
    335 uint32_t ExternalReferenceEncoder::Encode(Address address) const {
    336   DCHECK_NOT_NULL(address);
    337   HashMap::Entry* entry =
    338       const_cast<HashMap*>(map_)->Lookup(address, Hash(address));
    339   DCHECK_NOT_NULL(entry);
    340   return static_cast<uint32_t>(reinterpret_cast<intptr_t>(entry->value));
    341 }
    342 
    343 
    344 const char* ExternalReferenceEncoder::NameOfAddress(Isolate* isolate,
    345                                                     Address address) const {
    346   HashMap::Entry* entry =
    347       const_cast<HashMap*>(map_)->Lookup(address, Hash(address));
    348   if (entry == NULL) return "<unknown>";
    349   uint32_t i = static_cast<uint32_t>(reinterpret_cast<intptr_t>(entry->value));
    350   return ExternalReferenceTable::instance(isolate)->name(i);
    351 }
    352 
    353 
    354 class CodeAddressMap: public CodeEventLogger {
    355  public:
    356   explicit CodeAddressMap(Isolate* isolate)
    357       : isolate_(isolate) {
    358     isolate->logger()->addCodeEventListener(this);
    359   }
    360 
    361   ~CodeAddressMap() override {
    362     isolate_->logger()->removeCodeEventListener(this);
    363   }
    364 
    365   void CodeMoveEvent(Address from, Address to) override {
    366     address_to_name_map_.Move(from, to);
    367   }
    368 
    369   void CodeDisableOptEvent(Code* code, SharedFunctionInfo* shared) override {}
    370 
    371   void CodeDeleteEvent(Address from) override {
    372     address_to_name_map_.Remove(from);
    373   }
    374 
    375   const char* Lookup(Address address) {
    376     return address_to_name_map_.Lookup(address);
    377   }
    378 
    379  private:
    380   class NameMap {
    381    public:
    382     NameMap() : impl_(HashMap::PointersMatch) {}
    383 
    384     ~NameMap() {
    385       for (HashMap::Entry* p = impl_.Start(); p != NULL; p = impl_.Next(p)) {
    386         DeleteArray(static_cast<const char*>(p->value));
    387       }
    388     }
    389 
    390     void Insert(Address code_address, const char* name, int name_size) {
    391       HashMap::Entry* entry = FindOrCreateEntry(code_address);
    392       if (entry->value == NULL) {
    393         entry->value = CopyName(name, name_size);
    394       }
    395     }
    396 
    397     const char* Lookup(Address code_address) {
    398       HashMap::Entry* entry = FindEntry(code_address);
    399       return (entry != NULL) ? static_cast<const char*>(entry->value) : NULL;
    400     }
    401 
    402     void Remove(Address code_address) {
    403       HashMap::Entry* entry = FindEntry(code_address);
    404       if (entry != NULL) {
    405         DeleteArray(static_cast<char*>(entry->value));
    406         RemoveEntry(entry);
    407       }
    408     }
    409 
    410     void Move(Address from, Address to) {
    411       if (from == to) return;
    412       HashMap::Entry* from_entry = FindEntry(from);
    413       DCHECK(from_entry != NULL);
    414       void* value = from_entry->value;
    415       RemoveEntry(from_entry);
    416       HashMap::Entry* to_entry = FindOrCreateEntry(to);
    417       DCHECK(to_entry->value == NULL);
    418       to_entry->value = value;
    419     }
    420 
    421    private:
    422     static char* CopyName(const char* name, int name_size) {
    423       char* result = NewArray<char>(name_size + 1);
    424       for (int i = 0; i < name_size; ++i) {
    425         char c = name[i];
    426         if (c == '\0') c = ' ';
    427         result[i] = c;
    428       }
    429       result[name_size] = '\0';
    430       return result;
    431     }
    432 
    433     HashMap::Entry* FindOrCreateEntry(Address code_address) {
    434       return impl_.LookupOrInsert(code_address,
    435                                   ComputePointerHash(code_address));
    436     }
    437 
    438     HashMap::Entry* FindEntry(Address code_address) {
    439       return impl_.Lookup(code_address, ComputePointerHash(code_address));
    440     }
    441 
    442     void RemoveEntry(HashMap::Entry* entry) {
    443       impl_.Remove(entry->key, entry->hash);
    444     }
    445 
    446     HashMap impl_;
    447 
    448     DISALLOW_COPY_AND_ASSIGN(NameMap);
    449   };
    450 
    451   void LogRecordedBuffer(Code* code, SharedFunctionInfo*, const char* name,
    452                          int length) override {
    453     address_to_name_map_.Insert(code->address(), name, length);
    454   }
    455 
    456   NameMap address_to_name_map_;
    457   Isolate* isolate_;
    458 };
    459 
    460 
    461 void Deserializer::DecodeReservation(
    462     Vector<const SerializedData::Reservation> res) {
    463   DCHECK_EQ(0, reservations_[NEW_SPACE].length());
    464   STATIC_ASSERT(NEW_SPACE == 0);
    465   int current_space = NEW_SPACE;
    466   for (auto& r : res) {
    467     reservations_[current_space].Add({r.chunk_size(), NULL, NULL});
    468     if (r.is_last()) current_space++;
    469   }
    470   DCHECK_EQ(kNumberOfSpaces, current_space);
    471   for (int i = 0; i < kNumberOfPreallocatedSpaces; i++) current_chunk_[i] = 0;
    472 }
    473 
    474 
    475 void Deserializer::FlushICacheForNewIsolate() {
    476   DCHECK(!deserializing_user_code_);
    477   // The entire isolate is newly deserialized. Simply flush all code pages.
    478   PageIterator it(isolate_->heap()->code_space());
    479   while (it.has_next()) {
    480     Page* p = it.next();
    481     Assembler::FlushICache(isolate_, p->area_start(),
    482                            p->area_end() - p->area_start());
    483   }
    484 }
    485 
    486 
    487 void Deserializer::FlushICacheForNewCodeObjects() {
    488   DCHECK(deserializing_user_code_);
    489   for (Code* code : new_code_objects_) {
    490     Assembler::FlushICache(isolate_, code->instruction_start(),
    491                            code->instruction_size());
    492   }
    493 }
    494 
    495 
    496 bool Deserializer::ReserveSpace() {
    497 #ifdef DEBUG
    498   for (int i = NEW_SPACE; i < kNumberOfSpaces; ++i) {
    499     CHECK(reservations_[i].length() > 0);
    500   }
    501 #endif  // DEBUG
    502   if (!isolate_->heap()->ReserveSpace(reservations_)) return false;
    503   for (int i = 0; i < kNumberOfPreallocatedSpaces; i++) {
    504     high_water_[i] = reservations_[i][0].start;
    505   }
    506   return true;
    507 }
    508 
    509 
    510 void Deserializer::Initialize(Isolate* isolate) {
    511   DCHECK_NULL(isolate_);
    512   DCHECK_NOT_NULL(isolate);
    513   isolate_ = isolate;
    514   DCHECK_NULL(external_reference_table_);
    515   external_reference_table_ = ExternalReferenceTable::instance(isolate);
    516   CHECK_EQ(magic_number_,
    517            SerializedData::ComputeMagicNumber(external_reference_table_));
    518 }
    519 
    520 
    521 void Deserializer::Deserialize(Isolate* isolate) {
    522   Initialize(isolate);
    523   if (!ReserveSpace()) V8::FatalProcessOutOfMemory("deserializing context");
    524   // No active threads.
    525   DCHECK_NULL(isolate_->thread_manager()->FirstThreadStateInUse());
    526   // No active handles.
    527   DCHECK(isolate_->handle_scope_implementer()->blocks()->is_empty());
    528 
    529   {
    530     DisallowHeapAllocation no_gc;
    531     isolate_->heap()->IterateSmiRoots(this);
    532     isolate_->heap()->IterateStrongRoots(this, VISIT_ONLY_STRONG);
    533     isolate_->heap()->RepairFreeListsAfterDeserialization();
    534     isolate_->heap()->IterateWeakRoots(this, VISIT_ALL);
    535     DeserializeDeferredObjects();
    536     FlushICacheForNewIsolate();
    537   }
    538 
    539   isolate_->heap()->set_native_contexts_list(
    540       isolate_->heap()->undefined_value());
    541   // The allocation site list is build during root iteration, but if no sites
    542   // were encountered then it needs to be initialized to undefined.
    543   if (isolate_->heap()->allocation_sites_list() == Smi::FromInt(0)) {
    544     isolate_->heap()->set_allocation_sites_list(
    545         isolate_->heap()->undefined_value());
    546   }
    547 
    548   // Update data pointers to the external strings containing natives sources.
    549   Natives::UpdateSourceCache(isolate_->heap());
    550   ExtraNatives::UpdateSourceCache(isolate_->heap());
    551 
    552   // Issue code events for newly deserialized code objects.
    553   LOG_CODE_EVENT(isolate_, LogCodeObjects());
    554   LOG_CODE_EVENT(isolate_, LogCompiledFunctions());
    555 }
    556 
    557 
    558 MaybeHandle<Object> Deserializer::DeserializePartial(
    559     Isolate* isolate, Handle<JSGlobalProxy> global_proxy) {
    560   Initialize(isolate);
    561   if (!ReserveSpace()) {
    562     V8::FatalProcessOutOfMemory("deserialize context");
    563     return MaybeHandle<Object>();
    564   }
    565 
    566   Vector<Handle<Object> > attached_objects = Vector<Handle<Object> >::New(1);
    567   attached_objects[kGlobalProxyReference] = global_proxy;
    568   SetAttachedObjects(attached_objects);
    569 
    570   DisallowHeapAllocation no_gc;
    571   // Keep track of the code space start and end pointers in case new
    572   // code objects were unserialized
    573   OldSpace* code_space = isolate_->heap()->code_space();
    574   Address start_address = code_space->top();
    575   Object* root;
    576   VisitPointer(&root);
    577   DeserializeDeferredObjects();
    578 
    579   // There's no code deserialized here. If this assert fires then that's
    580   // changed and logging should be added to notify the profiler et al of the
    581   // new code, which also has to be flushed from instruction cache.
    582   CHECK_EQ(start_address, code_space->top());
    583   return Handle<Object>(root, isolate);
    584 }
    585 
    586 
    587 MaybeHandle<SharedFunctionInfo> Deserializer::DeserializeCode(
    588     Isolate* isolate) {
    589   Initialize(isolate);
    590   if (!ReserveSpace()) {
    591     return Handle<SharedFunctionInfo>();
    592   } else {
    593     deserializing_user_code_ = true;
    594     HandleScope scope(isolate);
    595     Handle<SharedFunctionInfo> result;
    596     {
    597       DisallowHeapAllocation no_gc;
    598       Object* root;
    599       VisitPointer(&root);
    600       DeserializeDeferredObjects();
    601       FlushICacheForNewCodeObjects();
    602       result = Handle<SharedFunctionInfo>(SharedFunctionInfo::cast(root));
    603     }
    604     CommitPostProcessedObjects(isolate);
    605     return scope.CloseAndEscape(result);
    606   }
    607 }
    608 
    609 
    610 Deserializer::~Deserializer() {
    611   // TODO(svenpanne) Re-enable this assertion when v8 initialization is fixed.
    612   // DCHECK(source_.AtEOF());
    613   attached_objects_.Dispose();
    614 }
    615 
    616 
    617 // This is called on the roots.  It is the driver of the deserialization
    618 // process.  It is also called on the body of each function.
    619 void Deserializer::VisitPointers(Object** start, Object** end) {
    620   // The space must be new space.  Any other space would cause ReadChunk to try
    621   // to update the remembered using NULL as the address.
    622   ReadData(start, end, NEW_SPACE, NULL);
    623 }
    624 
    625 
    626 void Deserializer::DeserializeDeferredObjects() {
    627   for (int code = source_.Get(); code != kSynchronize; code = source_.Get()) {
    628     switch (code) {
    629       case kAlignmentPrefix:
    630       case kAlignmentPrefix + 1:
    631       case kAlignmentPrefix + 2:
    632         SetAlignment(code);
    633         break;
    634       default: {
    635         int space = code & kSpaceMask;
    636         DCHECK(space <= kNumberOfSpaces);
    637         DCHECK(code - space == kNewObject);
    638         HeapObject* object = GetBackReferencedObject(space);
    639         int size = source_.GetInt() << kPointerSizeLog2;
    640         Address obj_address = object->address();
    641         Object** start = reinterpret_cast<Object**>(obj_address + kPointerSize);
    642         Object** end = reinterpret_cast<Object**>(obj_address + size);
    643         bool filled = ReadData(start, end, space, obj_address);
    644         CHECK(filled);
    645         DCHECK(CanBeDeferred(object));
    646         PostProcessNewObject(object, space);
    647       }
    648     }
    649   }
    650 }
    651 
    652 
    653 // Used to insert a deserialized internalized string into the string table.
    654 class StringTableInsertionKey : public HashTableKey {
    655  public:
    656   explicit StringTableInsertionKey(String* string)
    657       : string_(string), hash_(HashForObject(string)) {
    658     DCHECK(string->IsInternalizedString());
    659   }
    660 
    661   bool IsMatch(Object* string) override {
    662     // We know that all entries in a hash table had their hash keys created.
    663     // Use that knowledge to have fast failure.
    664     if (hash_ != HashForObject(string)) return false;
    665     // We want to compare the content of two internalized strings here.
    666     return string_->SlowEquals(String::cast(string));
    667   }
    668 
    669   uint32_t Hash() override { return hash_; }
    670 
    671   uint32_t HashForObject(Object* key) override {
    672     return String::cast(key)->Hash();
    673   }
    674 
    675   MUST_USE_RESULT Handle<Object> AsHandle(Isolate* isolate) override {
    676     return handle(string_, isolate);
    677   }
    678 
    679  private:
    680   String* string_;
    681   uint32_t hash_;
    682   DisallowHeapAllocation no_gc;
    683 };
    684 
    685 
    686 HeapObject* Deserializer::PostProcessNewObject(HeapObject* obj, int space) {
    687   if (deserializing_user_code()) {
    688     if (obj->IsString()) {
    689       String* string = String::cast(obj);
    690       // Uninitialize hash field as the hash seed may have changed.
    691       string->set_hash_field(String::kEmptyHashField);
    692       if (string->IsInternalizedString()) {
    693         // Canonicalize the internalized string. If it already exists in the
    694         // string table, set it to forward to the existing one.
    695         StringTableInsertionKey key(string);
    696         String* canonical = StringTable::LookupKeyIfExists(isolate_, &key);
    697         if (canonical == NULL) {
    698           new_internalized_strings_.Add(handle(string));
    699           return string;
    700         } else {
    701           string->SetForwardedInternalizedString(canonical);
    702           return canonical;
    703         }
    704       }
    705     } else if (obj->IsScript()) {
    706       new_scripts_.Add(handle(Script::cast(obj)));
    707     } else {
    708       DCHECK(CanBeDeferred(obj));
    709     }
    710   }
    711   if (obj->IsAllocationSite()) {
    712     DCHECK(obj->IsAllocationSite());
    713     // Allocation sites are present in the snapshot, and must be linked into
    714     // a list at deserialization time.
    715     AllocationSite* site = AllocationSite::cast(obj);
    716     // TODO(mvstanton): consider treating the heap()->allocation_sites_list()
    717     // as a (weak) root. If this root is relocated correctly, this becomes
    718     // unnecessary.
    719     if (isolate_->heap()->allocation_sites_list() == Smi::FromInt(0)) {
    720       site->set_weak_next(isolate_->heap()->undefined_value());
    721     } else {
    722       site->set_weak_next(isolate_->heap()->allocation_sites_list());
    723     }
    724     isolate_->heap()->set_allocation_sites_list(site);
    725   } else if (obj->IsCode()) {
    726     // We flush all code pages after deserializing the startup snapshot. In that
    727     // case, we only need to remember code objects in the large object space.
    728     // When deserializing user code, remember each individual code object.
    729     if (deserializing_user_code() || space == LO_SPACE) {
    730       new_code_objects_.Add(Code::cast(obj));
    731     }
    732   }
    733   // Check alignment.
    734   DCHECK_EQ(0, Heap::GetFillToAlign(obj->address(), obj->RequiredAlignment()));
    735   return obj;
    736 }
    737 
    738 
    739 void Deserializer::CommitPostProcessedObjects(Isolate* isolate) {
    740   StringTable::EnsureCapacityForDeserialization(
    741       isolate, new_internalized_strings_.length());
    742   for (Handle<String> string : new_internalized_strings_) {
    743     StringTableInsertionKey key(*string);
    744     DCHECK_NULL(StringTable::LookupKeyIfExists(isolate, &key));
    745     StringTable::LookupKey(isolate, &key);
    746   }
    747 
    748   Heap* heap = isolate->heap();
    749   Factory* factory = isolate->factory();
    750   for (Handle<Script> script : new_scripts_) {
    751     // Assign a new script id to avoid collision.
    752     script->set_id(isolate_->heap()->NextScriptId());
    753     // Add script to list.
    754     Handle<Object> list = WeakFixedArray::Add(factory->script_list(), script);
    755     heap->SetRootScriptList(*list);
    756   }
    757 }
    758 
    759 
    760 HeapObject* Deserializer::GetBackReferencedObject(int space) {
    761   HeapObject* obj;
    762   BackReference back_reference(source_.GetInt());
    763   if (space == LO_SPACE) {
    764     CHECK(back_reference.chunk_index() == 0);
    765     uint32_t index = back_reference.large_object_index();
    766     obj = deserialized_large_objects_[index];
    767   } else {
    768     DCHECK(space < kNumberOfPreallocatedSpaces);
    769     uint32_t chunk_index = back_reference.chunk_index();
    770     DCHECK_LE(chunk_index, current_chunk_[space]);
    771     uint32_t chunk_offset = back_reference.chunk_offset();
    772     Address address = reservations_[space][chunk_index].start + chunk_offset;
    773     if (next_alignment_ != kWordAligned) {
    774       int padding = Heap::GetFillToAlign(address, next_alignment_);
    775       next_alignment_ = kWordAligned;
    776       DCHECK(padding == 0 || HeapObject::FromAddress(address)->IsFiller());
    777       address += padding;
    778     }
    779     obj = HeapObject::FromAddress(address);
    780   }
    781   if (deserializing_user_code() && obj->IsInternalizedString()) {
    782     obj = String::cast(obj)->GetForwardedInternalizedString();
    783   }
    784   hot_objects_.Add(obj);
    785   return obj;
    786 }
    787 
    788 
    789 // This routine writes the new object into the pointer provided and then
    790 // returns true if the new object was in young space and false otherwise.
    791 // The reason for this strange interface is that otherwise the object is
    792 // written very late, which means the FreeSpace map is not set up by the
    793 // time we need to use it to mark the space at the end of a page free.
    794 void Deserializer::ReadObject(int space_number, Object** write_back) {
    795   Address address;
    796   HeapObject* obj;
    797   int size = source_.GetInt() << kObjectAlignmentBits;
    798 
    799   if (next_alignment_ != kWordAligned) {
    800     int reserved = size + Heap::GetMaximumFillToAlign(next_alignment_);
    801     address = Allocate(space_number, reserved);
    802     obj = HeapObject::FromAddress(address);
    803     // If one of the following assertions fails, then we are deserializing an
    804     // aligned object when the filler maps have not been deserialized yet.
    805     // We require filler maps as padding to align the object.
    806     Heap* heap = isolate_->heap();
    807     DCHECK(heap->free_space_map()->IsMap());
    808     DCHECK(heap->one_pointer_filler_map()->IsMap());
    809     DCHECK(heap->two_pointer_filler_map()->IsMap());
    810     obj = heap->AlignWithFiller(obj, size, reserved, next_alignment_);
    811     address = obj->address();
    812     next_alignment_ = kWordAligned;
    813   } else {
    814     address = Allocate(space_number, size);
    815     obj = HeapObject::FromAddress(address);
    816   }
    817 
    818   isolate_->heap()->OnAllocationEvent(obj, size);
    819   Object** current = reinterpret_cast<Object**>(address);
    820   Object** limit = current + (size >> kPointerSizeLog2);
    821   if (FLAG_log_snapshot_positions) {
    822     LOG(isolate_, SnapshotPositionEvent(address, source_.position()));
    823   }
    824 
    825   if (ReadData(current, limit, space_number, address)) {
    826     // Only post process if object content has not been deferred.
    827     obj = PostProcessNewObject(obj, space_number);
    828   }
    829 
    830   Object* write_back_obj = obj;
    831   UnalignedCopy(write_back, &write_back_obj);
    832 #ifdef DEBUG
    833   if (obj->IsCode()) {
    834     DCHECK(space_number == CODE_SPACE || space_number == LO_SPACE);
    835   } else {
    836     DCHECK(space_number != CODE_SPACE);
    837   }
    838 #endif  // DEBUG
    839 }
    840 
    841 
    842 // We know the space requirements before deserialization and can
    843 // pre-allocate that reserved space. During deserialization, all we need
    844 // to do is to bump up the pointer for each space in the reserved
    845 // space. This is also used for fixing back references.
    846 // We may have to split up the pre-allocation into several chunks
    847 // because it would not fit onto a single page. We do not have to keep
    848 // track of when to move to the next chunk. An opcode will signal this.
    849 // Since multiple large objects cannot be folded into one large object
    850 // space allocation, we have to do an actual allocation when deserializing
    851 // each large object. Instead of tracking offset for back references, we
    852 // reference large objects by index.
    853 Address Deserializer::Allocate(int space_index, int size) {
    854   if (space_index == LO_SPACE) {
    855     AlwaysAllocateScope scope(isolate_);
    856     LargeObjectSpace* lo_space = isolate_->heap()->lo_space();
    857     Executability exec = static_cast<Executability>(source_.Get());
    858     AllocationResult result = lo_space->AllocateRaw(size, exec);
    859     HeapObject* obj = HeapObject::cast(result.ToObjectChecked());
    860     deserialized_large_objects_.Add(obj);
    861     return obj->address();
    862   } else {
    863     DCHECK(space_index < kNumberOfPreallocatedSpaces);
    864     Address address = high_water_[space_index];
    865     DCHECK_NOT_NULL(address);
    866     high_water_[space_index] += size;
    867 #ifdef DEBUG
    868     // Assert that the current reserved chunk is still big enough.
    869     const Heap::Reservation& reservation = reservations_[space_index];
    870     int chunk_index = current_chunk_[space_index];
    871     CHECK_LE(high_water_[space_index], reservation[chunk_index].end);
    872 #endif
    873     return address;
    874   }
    875 }
    876 
    877 
    878 Object** Deserializer::CopyInNativesSource(Vector<const char> source_vector,
    879                                            Object** current) {
    880   DCHECK(!isolate_->heap()->deserialization_complete());
    881   NativesExternalStringResource* resource = new NativesExternalStringResource(
    882       source_vector.start(), source_vector.length());
    883   Object* resource_obj = reinterpret_cast<Object*>(resource);
    884   UnalignedCopy(current++, &resource_obj);
    885   return current;
    886 }
    887 
    888 
    889 bool Deserializer::ReadData(Object** current, Object** limit, int source_space,
    890                             Address current_object_address) {
    891   Isolate* const isolate = isolate_;
    892   // Write barrier support costs around 1% in startup time.  In fact there
    893   // are no new space objects in current boot snapshots, so it's not needed,
    894   // but that may change.
    895   bool write_barrier_needed =
    896       (current_object_address != NULL && source_space != NEW_SPACE &&
    897        source_space != CODE_SPACE);
    898   while (current < limit) {
    899     byte data = source_.Get();
    900     switch (data) {
    901 #define CASE_STATEMENT(where, how, within, space_number) \
    902   case where + how + within + space_number:              \
    903     STATIC_ASSERT((where & ~kWhereMask) == 0);           \
    904     STATIC_ASSERT((how & ~kHowToCodeMask) == 0);         \
    905     STATIC_ASSERT((within & ~kWhereToPointMask) == 0);   \
    906     STATIC_ASSERT((space_number & ~kSpaceMask) == 0);
    907 
    908 #define CASE_BODY(where, how, within, space_number_if_any)                     \
    909   {                                                                            \
    910     bool emit_write_barrier = false;                                           \
    911     bool current_was_incremented = false;                                      \
    912     int space_number = space_number_if_any == kAnyOldSpace                     \
    913                            ? (data & kSpaceMask)                               \
    914                            : space_number_if_any;                              \
    915     if (where == kNewObject && how == kPlain && within == kStartOfObject) {    \
    916       ReadObject(space_number, current);                                       \
    917       emit_write_barrier = (space_number == NEW_SPACE);                        \
    918     } else {                                                                   \
    919       Object* new_object = NULL; /* May not be a real Object pointer. */       \
    920       if (where == kNewObject) {                                               \
    921         ReadObject(space_number, &new_object);                                 \
    922       } else if (where == kBackref) {                                          \
    923         emit_write_barrier = (space_number == NEW_SPACE);                      \
    924         new_object = GetBackReferencedObject(data & kSpaceMask);               \
    925       } else if (where == kBackrefWithSkip) {                                  \
    926         int skip = source_.GetInt();                                           \
    927         current = reinterpret_cast<Object**>(                                  \
    928             reinterpret_cast<Address>(current) + skip);                        \
    929         emit_write_barrier = (space_number == NEW_SPACE);                      \
    930         new_object = GetBackReferencedObject(data & kSpaceMask);               \
    931       } else if (where == kRootArray) {                                        \
    932         int id = source_.GetInt();                                             \
    933         Heap::RootListIndex root_index = static_cast<Heap::RootListIndex>(id); \
    934         new_object = isolate->heap()->root(root_index);                        \
    935         emit_write_barrier = isolate->heap()->InNewSpace(new_object);          \
    936       } else if (where == kPartialSnapshotCache) {                             \
    937         int cache_index = source_.GetInt();                                    \
    938         new_object = isolate->partial_snapshot_cache()->at(cache_index);       \
    939         emit_write_barrier = isolate->heap()->InNewSpace(new_object);          \
    940       } else if (where == kExternalReference) {                                \
    941         int skip = source_.GetInt();                                           \
    942         current = reinterpret_cast<Object**>(                                  \
    943             reinterpret_cast<Address>(current) + skip);                        \
    944         int reference_id = source_.GetInt();                                   \
    945         Address address = external_reference_table_->address(reference_id);    \
    946         new_object = reinterpret_cast<Object*>(address);                       \
    947       } else if (where == kAttachedReference) {                                \
    948         int index = source_.GetInt();                                          \
    949         DCHECK(deserializing_user_code() || index == kGlobalProxyReference);   \
    950         new_object = *attached_objects_[index];                                \
    951         emit_write_barrier = isolate->heap()->InNewSpace(new_object);          \
    952       } else {                                                                 \
    953         DCHECK(where == kBuiltin);                                             \
    954         DCHECK(deserializing_user_code());                                     \
    955         int builtin_id = source_.GetInt();                                     \
    956         DCHECK_LE(0, builtin_id);                                              \
    957         DCHECK_LT(builtin_id, Builtins::builtin_count);                        \
    958         Builtins::Name name = static_cast<Builtins::Name>(builtin_id);         \
    959         new_object = isolate->builtins()->builtin(name);                       \
    960         emit_write_barrier = false;                                            \
    961       }                                                                        \
    962       if (within == kInnerPointer) {                                           \
    963         if (space_number != CODE_SPACE || new_object->IsCode()) {              \
    964           Code* new_code_object = reinterpret_cast<Code*>(new_object);         \
    965           new_object =                                                         \
    966               reinterpret_cast<Object*>(new_code_object->instruction_start()); \
    967         } else {                                                               \
    968           DCHECK(space_number == CODE_SPACE);                                  \
    969           Cell* cell = Cell::cast(new_object);                                 \
    970           new_object = reinterpret_cast<Object*>(cell->ValueAddress());        \
    971         }                                                                      \
    972       }                                                                        \
    973       if (how == kFromCode) {                                                  \
    974         Address location_of_branch_data = reinterpret_cast<Address>(current);  \
    975         Assembler::deserialization_set_special_target_at(                      \
    976             isolate, location_of_branch_data,                                  \
    977             Code::cast(HeapObject::FromAddress(current_object_address)),       \
    978             reinterpret_cast<Address>(new_object));                            \
    979         location_of_branch_data += Assembler::kSpecialTargetSize;              \
    980         current = reinterpret_cast<Object**>(location_of_branch_data);         \
    981         current_was_incremented = true;                                        \
    982       } else {                                                                 \
    983         UnalignedCopy(current, &new_object);                                   \
    984       }                                                                        \
    985     }                                                                          \
    986     if (emit_write_barrier && write_barrier_needed) {                          \
    987       Address current_address = reinterpret_cast<Address>(current);            \
    988       isolate->heap()->RecordWrite(                                            \
    989           current_object_address,                                              \
    990           static_cast<int>(current_address - current_object_address));         \
    991     }                                                                          \
    992     if (!current_was_incremented) {                                            \
    993       current++;                                                               \
    994     }                                                                          \
    995     break;                                                                     \
    996   }
    997 
    998 // This generates a case and a body for the new space (which has to do extra
    999 // write barrier handling) and handles the other spaces with fall-through cases
   1000 // and one body.
   1001 #define ALL_SPACES(where, how, within)           \
   1002   CASE_STATEMENT(where, how, within, NEW_SPACE)  \
   1003   CASE_BODY(where, how, within, NEW_SPACE)       \
   1004   CASE_STATEMENT(where, how, within, OLD_SPACE)  \
   1005   CASE_STATEMENT(where, how, within, CODE_SPACE) \
   1006   CASE_STATEMENT(where, how, within, MAP_SPACE)  \
   1007   CASE_STATEMENT(where, how, within, LO_SPACE)   \
   1008   CASE_BODY(where, how, within, kAnyOldSpace)
   1009 
   1010 #define FOUR_CASES(byte_code)             \
   1011   case byte_code:                         \
   1012   case byte_code + 1:                     \
   1013   case byte_code + 2:                     \
   1014   case byte_code + 3:
   1015 
   1016 #define SIXTEEN_CASES(byte_code)          \
   1017   FOUR_CASES(byte_code)                   \
   1018   FOUR_CASES(byte_code + 4)               \
   1019   FOUR_CASES(byte_code + 8)               \
   1020   FOUR_CASES(byte_code + 12)
   1021 
   1022 #define SINGLE_CASE(where, how, within, space) \
   1023   CASE_STATEMENT(where, how, within, space)    \
   1024   CASE_BODY(where, how, within, space)
   1025 
   1026       // Deserialize a new object and write a pointer to it to the current
   1027       // object.
   1028       ALL_SPACES(kNewObject, kPlain, kStartOfObject)
   1029       // Support for direct instruction pointers in functions.  It's an inner
   1030       // pointer because it points at the entry point, not at the start of the
   1031       // code object.
   1032       SINGLE_CASE(kNewObject, kPlain, kInnerPointer, CODE_SPACE)
   1033       // Deserialize a new code object and write a pointer to its first
   1034       // instruction to the current code object.
   1035       ALL_SPACES(kNewObject, kFromCode, kInnerPointer)
   1036       // Find a recently deserialized object using its offset from the current
   1037       // allocation point and write a pointer to it to the current object.
   1038       ALL_SPACES(kBackref, kPlain, kStartOfObject)
   1039       ALL_SPACES(kBackrefWithSkip, kPlain, kStartOfObject)
   1040 #if defined(V8_TARGET_ARCH_MIPS) || defined(V8_TARGET_ARCH_MIPS64) || \
   1041     defined(V8_TARGET_ARCH_PPC) || V8_EMBEDDED_CONSTANT_POOL
   1042       // Deserialize a new object from pointer found in code and write
   1043       // a pointer to it to the current object. Required only for MIPS, PPC or
   1044       // ARM with embedded constant pool, and omitted on the other architectures
   1045       // because it is fully unrolled and would cause bloat.
   1046       ALL_SPACES(kNewObject, kFromCode, kStartOfObject)
   1047       // Find a recently deserialized code object using its offset from the
   1048       // current allocation point and write a pointer to it to the current
   1049       // object. Required only for MIPS, PPC or ARM with embedded constant pool.
   1050       ALL_SPACES(kBackref, kFromCode, kStartOfObject)
   1051       ALL_SPACES(kBackrefWithSkip, kFromCode, kStartOfObject)
   1052 #endif
   1053       // Find a recently deserialized code object using its offset from the
   1054       // current allocation point and write a pointer to its first instruction
   1055       // to the current code object or the instruction pointer in a function
   1056       // object.
   1057       ALL_SPACES(kBackref, kFromCode, kInnerPointer)
   1058       ALL_SPACES(kBackrefWithSkip, kFromCode, kInnerPointer)
   1059       ALL_SPACES(kBackref, kPlain, kInnerPointer)
   1060       ALL_SPACES(kBackrefWithSkip, kPlain, kInnerPointer)
   1061       // Find an object in the roots array and write a pointer to it to the
   1062       // current object.
   1063       SINGLE_CASE(kRootArray, kPlain, kStartOfObject, 0)
   1064 #if defined(V8_TARGET_ARCH_MIPS) || defined(V8_TARGET_ARCH_MIPS64) || \
   1065     defined(V8_TARGET_ARCH_PPC) || V8_EMBEDDED_CONSTANT_POOL
   1066       // Find an object in the roots array and write a pointer to it to in code.
   1067       SINGLE_CASE(kRootArray, kFromCode, kStartOfObject, 0)
   1068 #endif
   1069       // Find an object in the partial snapshots cache and write a pointer to it
   1070       // to the current object.
   1071       SINGLE_CASE(kPartialSnapshotCache, kPlain, kStartOfObject, 0)
   1072       // Find an code entry in the partial snapshots cache and
   1073       // write a pointer to it to the current object.
   1074       SINGLE_CASE(kPartialSnapshotCache, kPlain, kInnerPointer, 0)
   1075       // Find an external reference and write a pointer to it to the current
   1076       // object.
   1077       SINGLE_CASE(kExternalReference, kPlain, kStartOfObject, 0)
   1078       // Find an external reference and write a pointer to it in the current
   1079       // code object.
   1080       SINGLE_CASE(kExternalReference, kFromCode, kStartOfObject, 0)
   1081       // Find an object in the attached references and write a pointer to it to
   1082       // the current object.
   1083       SINGLE_CASE(kAttachedReference, kPlain, kStartOfObject, 0)
   1084       SINGLE_CASE(kAttachedReference, kPlain, kInnerPointer, 0)
   1085       SINGLE_CASE(kAttachedReference, kFromCode, kInnerPointer, 0)
   1086       // Find a builtin and write a pointer to it to the current object.
   1087       SINGLE_CASE(kBuiltin, kPlain, kStartOfObject, 0)
   1088       SINGLE_CASE(kBuiltin, kPlain, kInnerPointer, 0)
   1089       SINGLE_CASE(kBuiltin, kFromCode, kInnerPointer, 0)
   1090 
   1091 #undef CASE_STATEMENT
   1092 #undef CASE_BODY
   1093 #undef ALL_SPACES
   1094 
   1095       case kSkip: {
   1096         int size = source_.GetInt();
   1097         current = reinterpret_cast<Object**>(
   1098             reinterpret_cast<intptr_t>(current) + size);
   1099         break;
   1100       }
   1101 
   1102       case kInternalReferenceEncoded:
   1103       case kInternalReference: {
   1104         // Internal reference address is not encoded via skip, but by offset
   1105         // from code entry.
   1106         int pc_offset = source_.GetInt();
   1107         int target_offset = source_.GetInt();
   1108         Code* code =
   1109             Code::cast(HeapObject::FromAddress(current_object_address));
   1110         DCHECK(0 <= pc_offset && pc_offset <= code->instruction_size());
   1111         DCHECK(0 <= target_offset && target_offset <= code->instruction_size());
   1112         Address pc = code->entry() + pc_offset;
   1113         Address target = code->entry() + target_offset;
   1114         Assembler::deserialization_set_target_internal_reference_at(
   1115             isolate, pc, target, data == kInternalReference
   1116                                      ? RelocInfo::INTERNAL_REFERENCE
   1117                                      : RelocInfo::INTERNAL_REFERENCE_ENCODED);
   1118         break;
   1119       }
   1120 
   1121       case kNop:
   1122         break;
   1123 
   1124       case kNextChunk: {
   1125         int space = source_.Get();
   1126         DCHECK(space < kNumberOfPreallocatedSpaces);
   1127         int chunk_index = current_chunk_[space];
   1128         const Heap::Reservation& reservation = reservations_[space];
   1129         // Make sure the current chunk is indeed exhausted.
   1130         CHECK_EQ(reservation[chunk_index].end, high_water_[space]);
   1131         // Move to next reserved chunk.
   1132         chunk_index = ++current_chunk_[space];
   1133         CHECK_LT(chunk_index, reservation.length());
   1134         high_water_[space] = reservation[chunk_index].start;
   1135         break;
   1136       }
   1137 
   1138       case kDeferred: {
   1139         // Deferred can only occur right after the heap object header.
   1140         DCHECK(current == reinterpret_cast<Object**>(current_object_address +
   1141                                                      kPointerSize));
   1142         HeapObject* obj = HeapObject::FromAddress(current_object_address);
   1143         // If the deferred object is a map, its instance type may be used
   1144         // during deserialization. Initialize it with a temporary value.
   1145         if (obj->IsMap()) Map::cast(obj)->set_instance_type(FILLER_TYPE);
   1146         current = limit;
   1147         return false;
   1148       }
   1149 
   1150       case kSynchronize:
   1151         // If we get here then that indicates that you have a mismatch between
   1152         // the number of GC roots when serializing and deserializing.
   1153         CHECK(false);
   1154         break;
   1155 
   1156       case kNativesStringResource:
   1157         current = CopyInNativesSource(Natives::GetScriptSource(source_.Get()),
   1158                                       current);
   1159         break;
   1160 
   1161       case kExtraNativesStringResource:
   1162         current = CopyInNativesSource(
   1163             ExtraNatives::GetScriptSource(source_.Get()), current);
   1164         break;
   1165 
   1166       // Deserialize raw data of variable length.
   1167       case kVariableRawData: {
   1168         int size_in_bytes = source_.GetInt();
   1169         byte* raw_data_out = reinterpret_cast<byte*>(current);
   1170         source_.CopyRaw(raw_data_out, size_in_bytes);
   1171         break;
   1172       }
   1173 
   1174       case kVariableRepeat: {
   1175         int repeats = source_.GetInt();
   1176         Object* object = current[-1];
   1177         DCHECK(!isolate->heap()->InNewSpace(object));
   1178         for (int i = 0; i < repeats; i++) UnalignedCopy(current++, &object);
   1179         break;
   1180       }
   1181 
   1182       case kAlignmentPrefix:
   1183       case kAlignmentPrefix + 1:
   1184       case kAlignmentPrefix + 2:
   1185         SetAlignment(data);
   1186         break;
   1187 
   1188       STATIC_ASSERT(kNumberOfRootArrayConstants == Heap::kOldSpaceRoots);
   1189       STATIC_ASSERT(kNumberOfRootArrayConstants == 32);
   1190       SIXTEEN_CASES(kRootArrayConstantsWithSkip)
   1191       SIXTEEN_CASES(kRootArrayConstantsWithSkip + 16) {
   1192         int skip = source_.GetInt();
   1193         current = reinterpret_cast<Object**>(
   1194             reinterpret_cast<intptr_t>(current) + skip);
   1195         // Fall through.
   1196       }
   1197 
   1198       SIXTEEN_CASES(kRootArrayConstants)
   1199       SIXTEEN_CASES(kRootArrayConstants + 16) {
   1200         int id = data & kRootArrayConstantsMask;
   1201         Heap::RootListIndex root_index = static_cast<Heap::RootListIndex>(id);
   1202         Object* object = isolate->heap()->root(root_index);
   1203         DCHECK(!isolate->heap()->InNewSpace(object));
   1204         UnalignedCopy(current++, &object);
   1205         break;
   1206       }
   1207 
   1208       STATIC_ASSERT(kNumberOfHotObjects == 8);
   1209       FOUR_CASES(kHotObjectWithSkip)
   1210       FOUR_CASES(kHotObjectWithSkip + 4) {
   1211         int skip = source_.GetInt();
   1212         current = reinterpret_cast<Object**>(
   1213             reinterpret_cast<Address>(current) + skip);
   1214         // Fall through.
   1215       }
   1216 
   1217       FOUR_CASES(kHotObject)
   1218       FOUR_CASES(kHotObject + 4) {
   1219         int index = data & kHotObjectMask;
   1220         Object* hot_object = hot_objects_.Get(index);
   1221         UnalignedCopy(current, &hot_object);
   1222         if (write_barrier_needed && isolate->heap()->InNewSpace(hot_object)) {
   1223           Address current_address = reinterpret_cast<Address>(current);
   1224           isolate->heap()->RecordWrite(
   1225               current_object_address,
   1226               static_cast<int>(current_address - current_object_address));
   1227         }
   1228         current++;
   1229         break;
   1230       }
   1231 
   1232       // Deserialize raw data of fixed length from 1 to 32 words.
   1233       STATIC_ASSERT(kNumberOfFixedRawData == 32);
   1234       SIXTEEN_CASES(kFixedRawData)
   1235       SIXTEEN_CASES(kFixedRawData + 16) {
   1236         byte* raw_data_out = reinterpret_cast<byte*>(current);
   1237         int size_in_bytes = (data - kFixedRawDataStart) << kPointerSizeLog2;
   1238         source_.CopyRaw(raw_data_out, size_in_bytes);
   1239         current = reinterpret_cast<Object**>(raw_data_out + size_in_bytes);
   1240         break;
   1241       }
   1242 
   1243       STATIC_ASSERT(kNumberOfFixedRepeat == 16);
   1244       SIXTEEN_CASES(kFixedRepeat) {
   1245         int repeats = data - kFixedRepeatStart;
   1246         Object* object;
   1247         UnalignedCopy(&object, current - 1);
   1248         DCHECK(!isolate->heap()->InNewSpace(object));
   1249         for (int i = 0; i < repeats; i++) UnalignedCopy(current++, &object);
   1250         break;
   1251       }
   1252 
   1253 #undef SIXTEEN_CASES
   1254 #undef FOUR_CASES
   1255 #undef SINGLE_CASE
   1256 
   1257       default:
   1258         CHECK(false);
   1259     }
   1260   }
   1261   CHECK_EQ(limit, current);
   1262   return true;
   1263 }
   1264 
   1265 
   1266 Serializer::Serializer(Isolate* isolate, SnapshotByteSink* sink)
   1267     : isolate_(isolate),
   1268       sink_(sink),
   1269       external_reference_encoder_(isolate),
   1270       root_index_map_(isolate),
   1271       recursion_depth_(0),
   1272       code_address_map_(NULL),
   1273       large_objects_total_size_(0),
   1274       seen_large_objects_index_(0) {
   1275   // The serializer is meant to be used only to generate initial heap images
   1276   // from a context in which there is only one isolate.
   1277   for (int i = 0; i < kNumberOfPreallocatedSpaces; i++) {
   1278     pending_chunk_[i] = 0;
   1279     max_chunk_size_[i] = static_cast<uint32_t>(
   1280         MemoryAllocator::PageAreaSize(static_cast<AllocationSpace>(i)));
   1281   }
   1282 
   1283 #ifdef OBJECT_PRINT
   1284   if (FLAG_serialization_statistics) {
   1285     instance_type_count_ = NewArray<int>(kInstanceTypes);
   1286     instance_type_size_ = NewArray<size_t>(kInstanceTypes);
   1287     for (int i = 0; i < kInstanceTypes; i++) {
   1288       instance_type_count_[i] = 0;
   1289       instance_type_size_[i] = 0;
   1290     }
   1291   } else {
   1292     instance_type_count_ = NULL;
   1293     instance_type_size_ = NULL;
   1294   }
   1295 #endif  // OBJECT_PRINT
   1296 }
   1297 
   1298 
   1299 Serializer::~Serializer() {
   1300   if (code_address_map_ != NULL) delete code_address_map_;
   1301 #ifdef OBJECT_PRINT
   1302   if (instance_type_count_ != NULL) {
   1303     DeleteArray(instance_type_count_);
   1304     DeleteArray(instance_type_size_);
   1305   }
   1306 #endif  // OBJECT_PRINT
   1307 }
   1308 
   1309 
   1310 #ifdef OBJECT_PRINT
   1311 void Serializer::CountInstanceType(Map* map, int size) {
   1312   int instance_type = map->instance_type();
   1313   instance_type_count_[instance_type]++;
   1314   instance_type_size_[instance_type] += size;
   1315 }
   1316 #endif  // OBJECT_PRINT
   1317 
   1318 
   1319 void Serializer::OutputStatistics(const char* name) {
   1320   if (!FLAG_serialization_statistics) return;
   1321   PrintF("%s:\n", name);
   1322   PrintF("  Spaces (bytes):\n");
   1323   for (int space = 0; space < kNumberOfSpaces; space++) {
   1324     PrintF("%16s", AllocationSpaceName(static_cast<AllocationSpace>(space)));
   1325   }
   1326   PrintF("\n");
   1327   for (int space = 0; space < kNumberOfPreallocatedSpaces; space++) {
   1328     size_t s = pending_chunk_[space];
   1329     for (uint32_t chunk_size : completed_chunks_[space]) s += chunk_size;
   1330     PrintF("%16" V8_PTR_PREFIX "d", s);
   1331   }
   1332   PrintF("%16d\n", large_objects_total_size_);
   1333 #ifdef OBJECT_PRINT
   1334   PrintF("  Instance types (count and bytes):\n");
   1335 #define PRINT_INSTANCE_TYPE(Name)                                          \
   1336   if (instance_type_count_[Name]) {                                        \
   1337     PrintF("%10d %10" V8_PTR_PREFIX "d  %s\n", instance_type_count_[Name], \
   1338            instance_type_size_[Name], #Name);                              \
   1339   }
   1340   INSTANCE_TYPE_LIST(PRINT_INSTANCE_TYPE)
   1341 #undef PRINT_INSTANCE_TYPE
   1342   PrintF("\n");
   1343 #endif  // OBJECT_PRINT
   1344 }
   1345 
   1346 
   1347 class Serializer::ObjectSerializer : public ObjectVisitor {
   1348  public:
   1349   ObjectSerializer(Serializer* serializer, Object* o, SnapshotByteSink* sink,
   1350                    HowToCode how_to_code, WhereToPoint where_to_point)
   1351       : serializer_(serializer),
   1352         object_(HeapObject::cast(o)),
   1353         sink_(sink),
   1354         reference_representation_(how_to_code + where_to_point),
   1355         bytes_processed_so_far_(0),
   1356         is_code_object_(o->IsCode()),
   1357         code_has_been_output_(false) {}
   1358   void Serialize();
   1359   void SerializeDeferred();
   1360   void VisitPointers(Object** start, Object** end) override;
   1361   void VisitEmbeddedPointer(RelocInfo* target) override;
   1362   void VisitExternalReference(Address* p) override;
   1363   void VisitExternalReference(RelocInfo* rinfo) override;
   1364   void VisitInternalReference(RelocInfo* rinfo) override;
   1365   void VisitCodeTarget(RelocInfo* target) override;
   1366   void VisitCodeEntry(Address entry_address) override;
   1367   void VisitCell(RelocInfo* rinfo) override;
   1368   void VisitRuntimeEntry(RelocInfo* reloc) override;
   1369   // Used for seralizing the external strings that hold the natives source.
   1370   void VisitExternalOneByteString(
   1371       v8::String::ExternalOneByteStringResource** resource) override;
   1372   // We can't serialize a heap with external two byte strings.
   1373   void VisitExternalTwoByteString(
   1374       v8::String::ExternalStringResource** resource) override {
   1375     UNREACHABLE();
   1376   }
   1377 
   1378  private:
   1379   void SerializePrologue(AllocationSpace space, int size, Map* map);
   1380 
   1381   bool SerializeExternalNativeSourceString(
   1382       int builtin_count,
   1383       v8::String::ExternalOneByteStringResource** resource_pointer,
   1384       FixedArray* source_cache, int resource_index);
   1385 
   1386   enum ReturnSkip { kCanReturnSkipInsteadOfSkipping, kIgnoringReturn };
   1387   // This function outputs or skips the raw data between the last pointer and
   1388   // up to the current position.  It optionally can just return the number of
   1389   // bytes to skip instead of performing a skip instruction, in case the skip
   1390   // can be merged into the next instruction.
   1391   int OutputRawData(Address up_to, ReturnSkip return_skip = kIgnoringReturn);
   1392   // External strings are serialized in a way to resemble sequential strings.
   1393   void SerializeExternalString();
   1394 
   1395   Address PrepareCode();
   1396 
   1397   Serializer* serializer_;
   1398   HeapObject* object_;
   1399   SnapshotByteSink* sink_;
   1400   int reference_representation_;
   1401   int bytes_processed_so_far_;
   1402   bool is_code_object_;
   1403   bool code_has_been_output_;
   1404 };
   1405 
   1406 
   1407 void Serializer::SerializeDeferredObjects() {
   1408   while (deferred_objects_.length() > 0) {
   1409     HeapObject* obj = deferred_objects_.RemoveLast();
   1410     ObjectSerializer obj_serializer(this, obj, sink_, kPlain, kStartOfObject);
   1411     obj_serializer.SerializeDeferred();
   1412   }
   1413   sink_->Put(kSynchronize, "Finished with deferred objects");
   1414 }
   1415 
   1416 
   1417 void StartupSerializer::SerializeStrongReferences() {
   1418   Isolate* isolate = this->isolate();
   1419   // No active threads.
   1420   CHECK_NULL(isolate->thread_manager()->FirstThreadStateInUse());
   1421   // No active or weak handles.
   1422   CHECK(isolate->handle_scope_implementer()->blocks()->is_empty());
   1423   CHECK_EQ(0, isolate->global_handles()->NumberOfWeakHandles());
   1424   CHECK_EQ(0, isolate->eternal_handles()->NumberOfHandles());
   1425   // We don't support serializing installed extensions.
   1426   CHECK(!isolate->has_installed_extensions());
   1427   isolate->heap()->IterateSmiRoots(this);
   1428   isolate->heap()->IterateStrongRoots(this, VISIT_ONLY_STRONG);
   1429 }
   1430 
   1431 
   1432 void StartupSerializer::VisitPointers(Object** start, Object** end) {
   1433   for (Object** current = start; current < end; current++) {
   1434     if (start == isolate()->heap()->roots_array_start()) {
   1435       root_index_wave_front_ =
   1436           Max(root_index_wave_front_, static_cast<intptr_t>(current - start));
   1437     }
   1438     if (ShouldBeSkipped(current)) {
   1439       sink_->Put(kSkip, "Skip");
   1440       sink_->PutInt(kPointerSize, "SkipOneWord");
   1441     } else if ((*current)->IsSmi()) {
   1442       sink_->Put(kOnePointerRawData, "Smi");
   1443       for (int i = 0; i < kPointerSize; i++) {
   1444         sink_->Put(reinterpret_cast<byte*>(current)[i], "Byte");
   1445       }
   1446     } else {
   1447       SerializeObject(HeapObject::cast(*current), kPlain, kStartOfObject, 0);
   1448     }
   1449   }
   1450 }
   1451 
   1452 
   1453 void PartialSerializer::Serialize(Object** o) {
   1454   if ((*o)->IsContext()) {
   1455     Context* context = Context::cast(*o);
   1456     global_object_ = context->global_object();
   1457     back_reference_map()->AddGlobalProxy(context->global_proxy());
   1458     // The bootstrap snapshot has a code-stub context. When serializing the
   1459     // partial snapshot, it is chained into the weak context list on the isolate
   1460     // and it's next context pointer may point to the code-stub context.  Clear
   1461     // it before serializing, it will get re-added to the context list
   1462     // explicitly when it's loaded.
   1463     if (context->IsNativeContext()) {
   1464       context->set(Context::NEXT_CONTEXT_LINK,
   1465                    isolate_->heap()->undefined_value());
   1466       DCHECK(!context->global_object()->IsUndefined());
   1467     }
   1468   }
   1469   VisitPointer(o);
   1470   SerializeDeferredObjects();
   1471   Pad();
   1472 }
   1473 
   1474 
   1475 bool Serializer::ShouldBeSkipped(Object** current) {
   1476   Object** roots = isolate()->heap()->roots_array_start();
   1477   return current == &roots[Heap::kStoreBufferTopRootIndex]
   1478       || current == &roots[Heap::kStackLimitRootIndex]
   1479       || current == &roots[Heap::kRealStackLimitRootIndex];
   1480 }
   1481 
   1482 
   1483 void Serializer::VisitPointers(Object** start, Object** end) {
   1484   for (Object** current = start; current < end; current++) {
   1485     if ((*current)->IsSmi()) {
   1486       sink_->Put(kOnePointerRawData, "Smi");
   1487       for (int i = 0; i < kPointerSize; i++) {
   1488         sink_->Put(reinterpret_cast<byte*>(current)[i], "Byte");
   1489       }
   1490     } else {
   1491       SerializeObject(HeapObject::cast(*current), kPlain, kStartOfObject, 0);
   1492     }
   1493   }
   1494 }
   1495 
   1496 
   1497 void Serializer::EncodeReservations(
   1498     List<SerializedData::Reservation>* out) const {
   1499   for (int i = 0; i < kNumberOfPreallocatedSpaces; i++) {
   1500     for (int j = 0; j < completed_chunks_[i].length(); j++) {
   1501       out->Add(SerializedData::Reservation(completed_chunks_[i][j]));
   1502     }
   1503 
   1504     if (pending_chunk_[i] > 0 || completed_chunks_[i].length() == 0) {
   1505       out->Add(SerializedData::Reservation(pending_chunk_[i]));
   1506     }
   1507     out->last().mark_as_last();
   1508   }
   1509 
   1510   out->Add(SerializedData::Reservation(large_objects_total_size_));
   1511   out->last().mark_as_last();
   1512 }
   1513 
   1514 
   1515 // This ensures that the partial snapshot cache keeps things alive during GC and
   1516 // tracks their movement.  When it is called during serialization of the startup
   1517 // snapshot nothing happens.  When the partial (context) snapshot is created,
   1518 // this array is populated with the pointers that the partial snapshot will
   1519 // need. As that happens we emit serialized objects to the startup snapshot
   1520 // that correspond to the elements of this cache array.  On deserialization we
   1521 // therefore need to visit the cache array.  This fills it up with pointers to
   1522 // deserialized objects.
   1523 void SerializerDeserializer::Iterate(Isolate* isolate,
   1524                                      ObjectVisitor* visitor) {
   1525   if (isolate->serializer_enabled()) return;
   1526   List<Object*>* cache = isolate->partial_snapshot_cache();
   1527   for (int i = 0;; ++i) {
   1528     // Extend the array ready to get a value when deserializing.
   1529     if (cache->length() <= i) cache->Add(Smi::FromInt(0));
   1530     visitor->VisitPointer(&cache->at(i));
   1531     // Sentinel is the undefined object, which is a root so it will not normally
   1532     // be found in the cache.
   1533     if (cache->at(i)->IsUndefined()) break;
   1534   }
   1535 }
   1536 
   1537 
   1538 bool SerializerDeserializer::CanBeDeferred(HeapObject* o) {
   1539   return !o->IsString() && !o->IsScript();
   1540 }
   1541 
   1542 
   1543 int PartialSerializer::PartialSnapshotCacheIndex(HeapObject* heap_object) {
   1544   Isolate* isolate = this->isolate();
   1545   List<Object*>* cache = isolate->partial_snapshot_cache();
   1546   int new_index = cache->length();
   1547 
   1548   int index = partial_cache_index_map_.LookupOrInsert(heap_object, new_index);
   1549   if (index == PartialCacheIndexMap::kInvalidIndex) {
   1550     // We didn't find the object in the cache.  So we add it to the cache and
   1551     // then visit the pointer so that it becomes part of the startup snapshot
   1552     // and we can refer to it from the partial snapshot.
   1553     cache->Add(heap_object);
   1554     startup_serializer_->VisitPointer(reinterpret_cast<Object**>(&heap_object));
   1555     // We don't recurse from the startup snapshot generator into the partial
   1556     // snapshot generator.
   1557     return new_index;
   1558   }
   1559   return index;
   1560 }
   1561 
   1562 
   1563 bool PartialSerializer::ShouldBeInThePartialSnapshotCache(HeapObject* o) {
   1564   // Scripts should be referred only through shared function infos.  We can't
   1565   // allow them to be part of the partial snapshot because they contain a
   1566   // unique ID, and deserializing several partial snapshots containing script
   1567   // would cause dupes.
   1568   DCHECK(!o->IsScript());
   1569   return o->IsName() || o->IsSharedFunctionInfo() || o->IsHeapNumber() ||
   1570          o->IsCode() || o->IsScopeInfo() || o->IsExecutableAccessorInfo() ||
   1571          o->map() ==
   1572              startup_serializer_->isolate()->heap()->fixed_cow_array_map();
   1573 }
   1574 
   1575 
   1576 #ifdef DEBUG
   1577 bool Serializer::BackReferenceIsAlreadyAllocated(BackReference reference) {
   1578   DCHECK(reference.is_valid());
   1579   DCHECK(!reference.is_source());
   1580   DCHECK(!reference.is_global_proxy());
   1581   AllocationSpace space = reference.space();
   1582   int chunk_index = reference.chunk_index();
   1583   if (space == LO_SPACE) {
   1584     return chunk_index == 0 &&
   1585            reference.large_object_index() < seen_large_objects_index_;
   1586   } else if (chunk_index == completed_chunks_[space].length()) {
   1587     return reference.chunk_offset() < pending_chunk_[space];
   1588   } else {
   1589     return chunk_index < completed_chunks_[space].length() &&
   1590            reference.chunk_offset() < completed_chunks_[space][chunk_index];
   1591   }
   1592 }
   1593 #endif  // DEBUG
   1594 
   1595 
   1596 bool Serializer::SerializeKnownObject(HeapObject* obj, HowToCode how_to_code,
   1597                                       WhereToPoint where_to_point, int skip) {
   1598   if (how_to_code == kPlain && where_to_point == kStartOfObject) {
   1599     // Encode a reference to a hot object by its index in the working set.
   1600     int index = hot_objects_.Find(obj);
   1601     if (index != HotObjectsList::kNotFound) {
   1602       DCHECK(index >= 0 && index < kNumberOfHotObjects);
   1603       if (FLAG_trace_serializer) {
   1604         PrintF(" Encoding hot object %d:", index);
   1605         obj->ShortPrint();
   1606         PrintF("\n");
   1607       }
   1608       if (skip != 0) {
   1609         sink_->Put(kHotObjectWithSkip + index, "HotObjectWithSkip");
   1610         sink_->PutInt(skip, "HotObjectSkipDistance");
   1611       } else {
   1612         sink_->Put(kHotObject + index, "HotObject");
   1613       }
   1614       return true;
   1615     }
   1616   }
   1617   BackReference back_reference = back_reference_map_.Lookup(obj);
   1618   if (back_reference.is_valid()) {
   1619     // Encode the location of an already deserialized object in order to write
   1620     // its location into a later object.  We can encode the location as an
   1621     // offset fromthe start of the deserialized objects or as an offset
   1622     // backwards from thecurrent allocation pointer.
   1623     if (back_reference.is_source()) {
   1624       FlushSkip(skip);
   1625       if (FLAG_trace_serializer) PrintF(" Encoding source object\n");
   1626       DCHECK(how_to_code == kPlain && where_to_point == kStartOfObject);
   1627       sink_->Put(kAttachedReference + kPlain + kStartOfObject, "Source");
   1628       sink_->PutInt(kSourceObjectReference, "kSourceObjectReference");
   1629     } else if (back_reference.is_global_proxy()) {
   1630       FlushSkip(skip);
   1631       if (FLAG_trace_serializer) PrintF(" Encoding global proxy\n");
   1632       DCHECK(how_to_code == kPlain && where_to_point == kStartOfObject);
   1633       sink_->Put(kAttachedReference + kPlain + kStartOfObject, "Global Proxy");
   1634       sink_->PutInt(kGlobalProxyReference, "kGlobalProxyReference");
   1635     } else {
   1636       if (FLAG_trace_serializer) {
   1637         PrintF(" Encoding back reference to: ");
   1638         obj->ShortPrint();
   1639         PrintF("\n");
   1640       }
   1641 
   1642       PutAlignmentPrefix(obj);
   1643       AllocationSpace space = back_reference.space();
   1644       if (skip == 0) {
   1645         sink_->Put(kBackref + how_to_code + where_to_point + space, "BackRef");
   1646       } else {
   1647         sink_->Put(kBackrefWithSkip + how_to_code + where_to_point + space,
   1648                    "BackRefWithSkip");
   1649         sink_->PutInt(skip, "BackRefSkipDistance");
   1650       }
   1651       PutBackReference(obj, back_reference);
   1652     }
   1653     return true;
   1654   }
   1655   return false;
   1656 }
   1657 
   1658 
   1659 StartupSerializer::StartupSerializer(Isolate* isolate, SnapshotByteSink* sink)
   1660     : Serializer(isolate, sink), root_index_wave_front_(0) {
   1661   // Clear the cache of objects used by the partial snapshot.  After the
   1662   // strong roots have been serialized we can create a partial snapshot
   1663   // which will repopulate the cache with objects needed by that partial
   1664   // snapshot.
   1665   isolate->partial_snapshot_cache()->Clear();
   1666   InitializeCodeAddressMap();
   1667 }
   1668 
   1669 
   1670 void StartupSerializer::SerializeObject(HeapObject* obj, HowToCode how_to_code,
   1671                                         WhereToPoint where_to_point, int skip) {
   1672   DCHECK(!obj->IsJSFunction());
   1673 
   1674   int root_index = root_index_map_.Lookup(obj);
   1675   // We can only encode roots as such if it has already been serialized.
   1676   // That applies to root indices below the wave front.
   1677   if (root_index != RootIndexMap::kInvalidRootIndex &&
   1678       root_index < root_index_wave_front_) {
   1679     PutRoot(root_index, obj, how_to_code, where_to_point, skip);
   1680     return;
   1681   }
   1682 
   1683   if (obj->IsCode() && Code::cast(obj)->kind() == Code::FUNCTION) {
   1684     obj = isolate()->builtins()->builtin(Builtins::kCompileLazy);
   1685   }
   1686 
   1687   if (SerializeKnownObject(obj, how_to_code, where_to_point, skip)) return;
   1688 
   1689   FlushSkip(skip);
   1690 
   1691   // Object has not yet been serialized.  Serialize it here.
   1692   ObjectSerializer object_serializer(this, obj, sink_, how_to_code,
   1693                                      where_to_point);
   1694   object_serializer.Serialize();
   1695 }
   1696 
   1697 
   1698 void StartupSerializer::SerializeWeakReferencesAndDeferred() {
   1699   // This phase comes right after the serialization (of the snapshot).
   1700   // After we have done the partial serialization the partial snapshot cache
   1701   // will contain some references needed to decode the partial snapshot.  We
   1702   // add one entry with 'undefined' which is the sentinel that the deserializer
   1703   // uses to know it is done deserializing the array.
   1704   Object* undefined = isolate()->heap()->undefined_value();
   1705   VisitPointer(&undefined);
   1706   isolate()->heap()->IterateWeakRoots(this, VISIT_ALL);
   1707   SerializeDeferredObjects();
   1708   Pad();
   1709 }
   1710 
   1711 
   1712 void Serializer::PutRoot(int root_index,
   1713                          HeapObject* object,
   1714                          SerializerDeserializer::HowToCode how_to_code,
   1715                          SerializerDeserializer::WhereToPoint where_to_point,
   1716                          int skip) {
   1717   if (FLAG_trace_serializer) {
   1718     PrintF(" Encoding root %d:", root_index);
   1719     object->ShortPrint();
   1720     PrintF("\n");
   1721   }
   1722 
   1723   if (how_to_code == kPlain && where_to_point == kStartOfObject &&
   1724       root_index < kNumberOfRootArrayConstants &&
   1725       !isolate()->heap()->InNewSpace(object)) {
   1726     if (skip == 0) {
   1727       sink_->Put(kRootArrayConstants + root_index, "RootConstant");
   1728     } else {
   1729       sink_->Put(kRootArrayConstantsWithSkip + root_index, "RootConstant");
   1730       sink_->PutInt(skip, "SkipInPutRoot");
   1731     }
   1732   } else {
   1733     FlushSkip(skip);
   1734     sink_->Put(kRootArray + how_to_code + where_to_point, "RootSerialization");
   1735     sink_->PutInt(root_index, "root_index");
   1736   }
   1737 }
   1738 
   1739 
   1740 void Serializer::PutBackReference(HeapObject* object, BackReference reference) {
   1741   DCHECK(BackReferenceIsAlreadyAllocated(reference));
   1742   sink_->PutInt(reference.reference(), "BackRefValue");
   1743   hot_objects_.Add(object);
   1744 }
   1745 
   1746 
   1747 int Serializer::PutAlignmentPrefix(HeapObject* object) {
   1748   AllocationAlignment alignment = object->RequiredAlignment();
   1749   if (alignment != kWordAligned) {
   1750     DCHECK(1 <= alignment && alignment <= 3);
   1751     byte prefix = (kAlignmentPrefix - 1) + alignment;
   1752     sink_->Put(prefix, "Alignment");
   1753     return Heap::GetMaximumFillToAlign(alignment);
   1754   }
   1755   return 0;
   1756 }
   1757 
   1758 
   1759 void PartialSerializer::SerializeObject(HeapObject* obj, HowToCode how_to_code,
   1760                                         WhereToPoint where_to_point, int skip) {
   1761   if (obj->IsMap()) {
   1762     // The code-caches link to context-specific code objects, which
   1763     // the startup and context serializes cannot currently handle.
   1764     DCHECK(Map::cast(obj)->code_cache() == obj->GetHeap()->empty_fixed_array());
   1765   }
   1766 
   1767   // Replace typed arrays by undefined.
   1768   if (obj->IsJSTypedArray()) obj = isolate_->heap()->undefined_value();
   1769 
   1770   int root_index = root_index_map_.Lookup(obj);
   1771   if (root_index != RootIndexMap::kInvalidRootIndex) {
   1772     PutRoot(root_index, obj, how_to_code, where_to_point, skip);
   1773     return;
   1774   }
   1775 
   1776   if (ShouldBeInThePartialSnapshotCache(obj)) {
   1777     FlushSkip(skip);
   1778 
   1779     int cache_index = PartialSnapshotCacheIndex(obj);
   1780     sink_->Put(kPartialSnapshotCache + how_to_code + where_to_point,
   1781                "PartialSnapshotCache");
   1782     sink_->PutInt(cache_index, "partial_snapshot_cache_index");
   1783     return;
   1784   }
   1785 
   1786   // Pointers from the partial snapshot to the objects in the startup snapshot
   1787   // should go through the root array or through the partial snapshot cache.
   1788   // If this is not the case you may have to add something to the root array.
   1789   DCHECK(!startup_serializer_->back_reference_map()->Lookup(obj).is_valid());
   1790   // All the internalized strings that the partial snapshot needs should be
   1791   // either in the root table or in the partial snapshot cache.
   1792   DCHECK(!obj->IsInternalizedString());
   1793 
   1794   if (SerializeKnownObject(obj, how_to_code, where_to_point, skip)) return;
   1795 
   1796   FlushSkip(skip);
   1797 
   1798   // Clear literal boilerplates.
   1799   if (obj->IsJSFunction()) {
   1800     FixedArray* literals = JSFunction::cast(obj)->literals();
   1801     for (int i = 0; i < literals->length(); i++) literals->set_undefined(i);
   1802   }
   1803 
   1804   // Object has not yet been serialized.  Serialize it here.
   1805   ObjectSerializer serializer(this, obj, sink_, how_to_code, where_to_point);
   1806   serializer.Serialize();
   1807 }
   1808 
   1809 
   1810 void Serializer::ObjectSerializer::SerializePrologue(AllocationSpace space,
   1811                                                      int size, Map* map) {
   1812   if (serializer_->code_address_map_) {
   1813     const char* code_name =
   1814         serializer_->code_address_map_->Lookup(object_->address());
   1815     LOG(serializer_->isolate_,
   1816         CodeNameEvent(object_->address(), sink_->Position(), code_name));
   1817     LOG(serializer_->isolate_,
   1818         SnapshotPositionEvent(object_->address(), sink_->Position()));
   1819   }
   1820 
   1821   BackReference back_reference;
   1822   if (space == LO_SPACE) {
   1823     sink_->Put(kNewObject + reference_representation_ + space,
   1824                "NewLargeObject");
   1825     sink_->PutInt(size >> kObjectAlignmentBits, "ObjectSizeInWords");
   1826     if (object_->IsCode()) {
   1827       sink_->Put(EXECUTABLE, "executable large object");
   1828     } else {
   1829       sink_->Put(NOT_EXECUTABLE, "not executable large object");
   1830     }
   1831     back_reference = serializer_->AllocateLargeObject(size);
   1832   } else {
   1833     int fill = serializer_->PutAlignmentPrefix(object_);
   1834     back_reference = serializer_->Allocate(space, size + fill);
   1835     sink_->Put(kNewObject + reference_representation_ + space, "NewObject");
   1836     sink_->PutInt(size >> kObjectAlignmentBits, "ObjectSizeInWords");
   1837   }
   1838 
   1839 #ifdef OBJECT_PRINT
   1840   if (FLAG_serialization_statistics) {
   1841     serializer_->CountInstanceType(map, size);
   1842   }
   1843 #endif  // OBJECT_PRINT
   1844 
   1845   // Mark this object as already serialized.
   1846   serializer_->back_reference_map()->Add(object_, back_reference);
   1847 
   1848   // Serialize the map (first word of the object).
   1849   serializer_->SerializeObject(map, kPlain, kStartOfObject, 0);
   1850 }
   1851 
   1852 
   1853 void Serializer::ObjectSerializer::SerializeExternalString() {
   1854   // Instead of serializing this as an external string, we serialize
   1855   // an imaginary sequential string with the same content.
   1856   Isolate* isolate = serializer_->isolate();
   1857   DCHECK(object_->IsExternalString());
   1858   DCHECK(object_->map() != isolate->heap()->native_source_string_map());
   1859   ExternalString* string = ExternalString::cast(object_);
   1860   int length = string->length();
   1861   Map* map;
   1862   int content_size;
   1863   int allocation_size;
   1864   const byte* resource;
   1865   // Find the map and size for the imaginary sequential string.
   1866   bool internalized = object_->IsInternalizedString();
   1867   if (object_->IsExternalOneByteString()) {
   1868     map = internalized ? isolate->heap()->one_byte_internalized_string_map()
   1869                        : isolate->heap()->one_byte_string_map();
   1870     allocation_size = SeqOneByteString::SizeFor(length);
   1871     content_size = length * kCharSize;
   1872     resource = reinterpret_cast<const byte*>(
   1873         ExternalOneByteString::cast(string)->resource()->data());
   1874   } else {
   1875     map = internalized ? isolate->heap()->internalized_string_map()
   1876                        : isolate->heap()->string_map();
   1877     allocation_size = SeqTwoByteString::SizeFor(length);
   1878     content_size = length * kShortSize;
   1879     resource = reinterpret_cast<const byte*>(
   1880         ExternalTwoByteString::cast(string)->resource()->data());
   1881   }
   1882 
   1883   AllocationSpace space = (allocation_size > Page::kMaxRegularHeapObjectSize)
   1884                               ? LO_SPACE
   1885                               : OLD_SPACE;
   1886   SerializePrologue(space, allocation_size, map);
   1887 
   1888   // Output the rest of the imaginary string.
   1889   int bytes_to_output = allocation_size - HeapObject::kHeaderSize;
   1890 
   1891   // Output raw data header. Do not bother with common raw length cases here.
   1892   sink_->Put(kVariableRawData, "RawDataForString");
   1893   sink_->PutInt(bytes_to_output, "length");
   1894 
   1895   // Serialize string header (except for map).
   1896   Address string_start = string->address();
   1897   for (int i = HeapObject::kHeaderSize; i < SeqString::kHeaderSize; i++) {
   1898     sink_->PutSection(string_start[i], "StringHeader");
   1899   }
   1900 
   1901   // Serialize string content.
   1902   sink_->PutRaw(resource, content_size, "StringContent");
   1903 
   1904   // Since the allocation size is rounded up to object alignment, there
   1905   // maybe left-over bytes that need to be padded.
   1906   int padding_size = allocation_size - SeqString::kHeaderSize - content_size;
   1907   DCHECK(0 <= padding_size && padding_size < kObjectAlignment);
   1908   for (int i = 0; i < padding_size; i++) sink_->PutSection(0, "StringPadding");
   1909 
   1910   sink_->Put(kSkip, "SkipAfterString");
   1911   sink_->PutInt(bytes_to_output, "SkipDistance");
   1912 }
   1913 
   1914 
   1915 // Clear and later restore the next link in the weak cell, if the object is one.
   1916 class UnlinkWeakCellScope {
   1917  public:
   1918   explicit UnlinkWeakCellScope(HeapObject* object) : weak_cell_(NULL) {
   1919     if (object->IsWeakCell()) {
   1920       weak_cell_ = WeakCell::cast(object);
   1921       next_ = weak_cell_->next();
   1922       weak_cell_->clear_next(object->GetHeap()->the_hole_value());
   1923     }
   1924   }
   1925 
   1926   ~UnlinkWeakCellScope() {
   1927     if (weak_cell_) weak_cell_->set_next(next_, UPDATE_WEAK_WRITE_BARRIER);
   1928   }
   1929 
   1930  private:
   1931   WeakCell* weak_cell_;
   1932   Object* next_;
   1933   DisallowHeapAllocation no_gc_;
   1934 };
   1935 
   1936 
   1937 void Serializer::ObjectSerializer::Serialize() {
   1938   if (FLAG_trace_serializer) {
   1939     PrintF(" Encoding heap object: ");
   1940     object_->ShortPrint();
   1941     PrintF("\n");
   1942   }
   1943 
   1944   // We cannot serialize typed array objects correctly.
   1945   DCHECK(!object_->IsJSTypedArray());
   1946 
   1947   // We don't expect fillers.
   1948   DCHECK(!object_->IsFiller());
   1949 
   1950   if (object_->IsScript()) {
   1951     // Clear cached line ends.
   1952     Object* undefined = serializer_->isolate()->heap()->undefined_value();
   1953     Script::cast(object_)->set_line_ends(undefined);
   1954   }
   1955 
   1956   if (object_->IsExternalString()) {
   1957     Heap* heap = serializer_->isolate()->heap();
   1958     if (object_->map() != heap->native_source_string_map()) {
   1959       // Usually we cannot recreate resources for external strings. To work
   1960       // around this, external strings are serialized to look like ordinary
   1961       // sequential strings.
   1962       // The exception are native source code strings, since we can recreate
   1963       // their resources. In that case we fall through and leave it to
   1964       // VisitExternalOneByteString further down.
   1965       SerializeExternalString();
   1966       return;
   1967     }
   1968   }
   1969 
   1970   int size = object_->Size();
   1971   Map* map = object_->map();
   1972   AllocationSpace space =
   1973       MemoryChunk::FromAddress(object_->address())->owner()->identity();
   1974   SerializePrologue(space, size, map);
   1975 
   1976   // Serialize the rest of the object.
   1977   CHECK_EQ(0, bytes_processed_so_far_);
   1978   bytes_processed_so_far_ = kPointerSize;
   1979 
   1980   RecursionScope recursion(serializer_);
   1981   // Objects that are immediately post processed during deserialization
   1982   // cannot be deferred, since post processing requires the object content.
   1983   if (recursion.ExceedsMaximum() && CanBeDeferred(object_)) {
   1984     serializer_->QueueDeferredObject(object_);
   1985     sink_->Put(kDeferred, "Deferring object content");
   1986     return;
   1987   }
   1988 
   1989   UnlinkWeakCellScope unlink_weak_cell(object_);
   1990 
   1991   object_->IterateBody(map->instance_type(), size, this);
   1992   OutputRawData(object_->address() + size);
   1993 }
   1994 
   1995 
   1996 void Serializer::ObjectSerializer::SerializeDeferred() {
   1997   if (FLAG_trace_serializer) {
   1998     PrintF(" Encoding deferred heap object: ");
   1999     object_->ShortPrint();
   2000     PrintF("\n");
   2001   }
   2002 
   2003   int size = object_->Size();
   2004   Map* map = object_->map();
   2005   BackReference reference = serializer_->back_reference_map()->Lookup(object_);
   2006 
   2007   // Serialize the rest of the object.
   2008   CHECK_EQ(0, bytes_processed_so_far_);
   2009   bytes_processed_so_far_ = kPointerSize;
   2010 
   2011   serializer_->PutAlignmentPrefix(object_);
   2012   sink_->Put(kNewObject + reference.space(), "deferred object");
   2013   serializer_->PutBackReference(object_, reference);
   2014   sink_->PutInt(size >> kPointerSizeLog2, "deferred object size");
   2015 
   2016   UnlinkWeakCellScope unlink_weak_cell(object_);
   2017 
   2018   object_->IterateBody(map->instance_type(), size, this);
   2019   OutputRawData(object_->address() + size);
   2020 }
   2021 
   2022 
   2023 void Serializer::ObjectSerializer::VisitPointers(Object** start,
   2024                                                  Object** end) {
   2025   Object** current = start;
   2026   while (current < end) {
   2027     while (current < end && (*current)->IsSmi()) current++;
   2028     if (current < end) OutputRawData(reinterpret_cast<Address>(current));
   2029 
   2030     while (current < end && !(*current)->IsSmi()) {
   2031       HeapObject* current_contents = HeapObject::cast(*current);
   2032       int root_index = serializer_->root_index_map()->Lookup(current_contents);
   2033       // Repeats are not subject to the write barrier so we can only use
   2034       // immortal immovable root members. They are never in new space.
   2035       if (current != start && root_index != RootIndexMap::kInvalidRootIndex &&
   2036           Heap::RootIsImmortalImmovable(root_index) &&
   2037           current_contents == current[-1]) {
   2038         DCHECK(!serializer_->isolate()->heap()->InNewSpace(current_contents));
   2039         int repeat_count = 1;
   2040         while (&current[repeat_count] < end - 1 &&
   2041                current[repeat_count] == current_contents) {
   2042           repeat_count++;
   2043         }
   2044         current += repeat_count;
   2045         bytes_processed_so_far_ += repeat_count * kPointerSize;
   2046         if (repeat_count > kNumberOfFixedRepeat) {
   2047           sink_->Put(kVariableRepeat, "VariableRepeat");
   2048           sink_->PutInt(repeat_count, "repeat count");
   2049         } else {
   2050           sink_->Put(kFixedRepeatStart + repeat_count, "FixedRepeat");
   2051         }
   2052       } else {
   2053         serializer_->SerializeObject(
   2054                 current_contents, kPlain, kStartOfObject, 0);
   2055         bytes_processed_so_far_ += kPointerSize;
   2056         current++;
   2057       }
   2058     }
   2059   }
   2060 }
   2061 
   2062 
   2063 void Serializer::ObjectSerializer::VisitEmbeddedPointer(RelocInfo* rinfo) {
   2064   int skip = OutputRawData(rinfo->target_address_address(),
   2065                            kCanReturnSkipInsteadOfSkipping);
   2066   HowToCode how_to_code = rinfo->IsCodedSpecially() ? kFromCode : kPlain;
   2067   Object* object = rinfo->target_object();
   2068   serializer_->SerializeObject(HeapObject::cast(object), how_to_code,
   2069                                kStartOfObject, skip);
   2070   bytes_processed_so_far_ += rinfo->target_address_size();
   2071 }
   2072 
   2073 
   2074 void Serializer::ObjectSerializer::VisitExternalReference(Address* p) {
   2075   int skip = OutputRawData(reinterpret_cast<Address>(p),
   2076                            kCanReturnSkipInsteadOfSkipping);
   2077   sink_->Put(kExternalReference + kPlain + kStartOfObject, "ExternalRef");
   2078   sink_->PutInt(skip, "SkipB4ExternalRef");
   2079   Address target = *p;
   2080   sink_->PutInt(serializer_->EncodeExternalReference(target), "reference id");
   2081   bytes_processed_so_far_ += kPointerSize;
   2082 }
   2083 
   2084 
   2085 void Serializer::ObjectSerializer::VisitExternalReference(RelocInfo* rinfo) {
   2086   int skip = OutputRawData(rinfo->target_address_address(),
   2087                            kCanReturnSkipInsteadOfSkipping);
   2088   HowToCode how_to_code = rinfo->IsCodedSpecially() ? kFromCode : kPlain;
   2089   sink_->Put(kExternalReference + how_to_code + kStartOfObject, "ExternalRef");
   2090   sink_->PutInt(skip, "SkipB4ExternalRef");
   2091   Address target = rinfo->target_external_reference();
   2092   sink_->PutInt(serializer_->EncodeExternalReference(target), "reference id");
   2093   bytes_processed_so_far_ += rinfo->target_address_size();
   2094 }
   2095 
   2096 
   2097 void Serializer::ObjectSerializer::VisitInternalReference(RelocInfo* rinfo) {
   2098   // We can only reference to internal references of code that has been output.
   2099   DCHECK(is_code_object_ && code_has_been_output_);
   2100   // We do not use skip from last patched pc to find the pc to patch, since
   2101   // target_address_address may not return addresses in ascending order when
   2102   // used for internal references. External references may be stored at the
   2103   // end of the code in the constant pool, whereas internal references are
   2104   // inline. That would cause the skip to be negative. Instead, we store the
   2105   // offset from code entry.
   2106   Address entry = Code::cast(object_)->entry();
   2107   intptr_t pc_offset = rinfo->target_internal_reference_address() - entry;
   2108   intptr_t target_offset = rinfo->target_internal_reference() - entry;
   2109   DCHECK(0 <= pc_offset &&
   2110          pc_offset <= Code::cast(object_)->instruction_size());
   2111   DCHECK(0 <= target_offset &&
   2112          target_offset <= Code::cast(object_)->instruction_size());
   2113   sink_->Put(rinfo->rmode() == RelocInfo::INTERNAL_REFERENCE
   2114                  ? kInternalReference
   2115                  : kInternalReferenceEncoded,
   2116              "InternalRef");
   2117   sink_->PutInt(static_cast<uintptr_t>(pc_offset), "internal ref address");
   2118   sink_->PutInt(static_cast<uintptr_t>(target_offset), "internal ref value");
   2119 }
   2120 
   2121 
   2122 void Serializer::ObjectSerializer::VisitRuntimeEntry(RelocInfo* rinfo) {
   2123   int skip = OutputRawData(rinfo->target_address_address(),
   2124                            kCanReturnSkipInsteadOfSkipping);
   2125   HowToCode how_to_code = rinfo->IsCodedSpecially() ? kFromCode : kPlain;
   2126   sink_->Put(kExternalReference + how_to_code + kStartOfObject, "ExternalRef");
   2127   sink_->PutInt(skip, "SkipB4ExternalRef");
   2128   Address target = rinfo->target_address();
   2129   sink_->PutInt(serializer_->EncodeExternalReference(target), "reference id");
   2130   bytes_processed_so_far_ += rinfo->target_address_size();
   2131 }
   2132 
   2133 
   2134 void Serializer::ObjectSerializer::VisitCodeTarget(RelocInfo* rinfo) {
   2135   int skip = OutputRawData(rinfo->target_address_address(),
   2136                            kCanReturnSkipInsteadOfSkipping);
   2137   Code* object = Code::GetCodeFromTargetAddress(rinfo->target_address());
   2138   serializer_->SerializeObject(object, kFromCode, kInnerPointer, skip);
   2139   bytes_processed_so_far_ += rinfo->target_address_size();
   2140 }
   2141 
   2142 
   2143 void Serializer::ObjectSerializer::VisitCodeEntry(Address entry_address) {
   2144   int skip = OutputRawData(entry_address, kCanReturnSkipInsteadOfSkipping);
   2145   Code* object = Code::cast(Code::GetObjectFromEntryAddress(entry_address));
   2146   serializer_->SerializeObject(object, kPlain, kInnerPointer, skip);
   2147   bytes_processed_so_far_ += kPointerSize;
   2148 }
   2149 
   2150 
   2151 void Serializer::ObjectSerializer::VisitCell(RelocInfo* rinfo) {
   2152   int skip = OutputRawData(rinfo->pc(), kCanReturnSkipInsteadOfSkipping);
   2153   Cell* object = Cell::cast(rinfo->target_cell());
   2154   serializer_->SerializeObject(object, kPlain, kInnerPointer, skip);
   2155   bytes_processed_so_far_ += kPointerSize;
   2156 }
   2157 
   2158 
   2159 bool Serializer::ObjectSerializer::SerializeExternalNativeSourceString(
   2160     int builtin_count,
   2161     v8::String::ExternalOneByteStringResource** resource_pointer,
   2162     FixedArray* source_cache, int resource_index) {
   2163   for (int i = 0; i < builtin_count; i++) {
   2164     Object* source = source_cache->get(i);
   2165     if (!source->IsUndefined()) {
   2166       ExternalOneByteString* string = ExternalOneByteString::cast(source);
   2167       typedef v8::String::ExternalOneByteStringResource Resource;
   2168       const Resource* resource = string->resource();
   2169       if (resource == *resource_pointer) {
   2170         sink_->Put(resource_index, "NativesStringResource");
   2171         sink_->PutSection(i, "NativesStringResourceEnd");
   2172         bytes_processed_so_far_ += sizeof(resource);
   2173         return true;
   2174       }
   2175     }
   2176   }
   2177   return false;
   2178 }
   2179 
   2180 
   2181 void Serializer::ObjectSerializer::VisitExternalOneByteString(
   2182     v8::String::ExternalOneByteStringResource** resource_pointer) {
   2183   Address references_start = reinterpret_cast<Address>(resource_pointer);
   2184   OutputRawData(references_start);
   2185   if (SerializeExternalNativeSourceString(
   2186           Natives::GetBuiltinsCount(), resource_pointer,
   2187           Natives::GetSourceCache(serializer_->isolate()->heap()),
   2188           kNativesStringResource)) {
   2189     return;
   2190   }
   2191   if (SerializeExternalNativeSourceString(
   2192           ExtraNatives::GetBuiltinsCount(), resource_pointer,
   2193           ExtraNatives::GetSourceCache(serializer_->isolate()->heap()),
   2194           kExtraNativesStringResource)) {
   2195     return;
   2196   }
   2197   // One of the strings in the natives cache should match the resource.  We
   2198   // don't expect any other kinds of external strings here.
   2199   UNREACHABLE();
   2200 }
   2201 
   2202 
   2203 Address Serializer::ObjectSerializer::PrepareCode() {
   2204   // To make snapshots reproducible, we make a copy of the code object
   2205   // and wipe all pointers in the copy, which we then serialize.
   2206   Code* original = Code::cast(object_);
   2207   Code* code = serializer_->CopyCode(original);
   2208   // Code age headers are not serializable.
   2209   code->MakeYoung(serializer_->isolate());
   2210   int mode_mask = RelocInfo::kCodeTargetMask |
   2211                   RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT) |
   2212                   RelocInfo::ModeMask(RelocInfo::EXTERNAL_REFERENCE) |
   2213                   RelocInfo::ModeMask(RelocInfo::RUNTIME_ENTRY) |
   2214                   RelocInfo::ModeMask(RelocInfo::INTERNAL_REFERENCE) |
   2215                   RelocInfo::ModeMask(RelocInfo::INTERNAL_REFERENCE_ENCODED);
   2216   for (RelocIterator it(code, mode_mask); !it.done(); it.next()) {
   2217     RelocInfo* rinfo = it.rinfo();
   2218     rinfo->WipeOut();
   2219   }
   2220   // We need to wipe out the header fields *after* wiping out the
   2221   // relocations, because some of these fields are needed for the latter.
   2222   code->WipeOutHeader();
   2223   return code->address();
   2224 }
   2225 
   2226 
   2227 int Serializer::ObjectSerializer::OutputRawData(
   2228     Address up_to, Serializer::ObjectSerializer::ReturnSkip return_skip) {
   2229   Address object_start = object_->address();
   2230   int base = bytes_processed_so_far_;
   2231   int up_to_offset = static_cast<int>(up_to - object_start);
   2232   int to_skip = up_to_offset - bytes_processed_so_far_;
   2233   int bytes_to_output = to_skip;
   2234   bytes_processed_so_far_ += to_skip;
   2235   // This assert will fail if the reloc info gives us the target_address_address
   2236   // locations in a non-ascending order.  Luckily that doesn't happen.
   2237   DCHECK(to_skip >= 0);
   2238   bool outputting_code = false;
   2239   if (to_skip != 0 && is_code_object_ && !code_has_been_output_) {
   2240     // Output the code all at once and fix later.
   2241     bytes_to_output = object_->Size() + to_skip - bytes_processed_so_far_;
   2242     outputting_code = true;
   2243     code_has_been_output_ = true;
   2244   }
   2245   if (bytes_to_output != 0 && (!is_code_object_ || outputting_code)) {
   2246     if (!outputting_code && bytes_to_output == to_skip &&
   2247         IsAligned(bytes_to_output, kPointerAlignment) &&
   2248         bytes_to_output <= kNumberOfFixedRawData * kPointerSize) {
   2249       int size_in_words = bytes_to_output >> kPointerSizeLog2;
   2250       sink_->PutSection(kFixedRawDataStart + size_in_words, "FixedRawData");
   2251       to_skip = 0;  // This instruction includes skip.
   2252     } else {
   2253       // We always end up here if we are outputting the code of a code object.
   2254       sink_->Put(kVariableRawData, "VariableRawData");
   2255       sink_->PutInt(bytes_to_output, "length");
   2256     }
   2257 
   2258     if (is_code_object_) object_start = PrepareCode();
   2259 
   2260     const char* description = is_code_object_ ? "Code" : "Byte";
   2261     sink_->PutRaw(object_start + base, bytes_to_output, description);
   2262   }
   2263   if (to_skip != 0 && return_skip == kIgnoringReturn) {
   2264     sink_->Put(kSkip, "Skip");
   2265     sink_->PutInt(to_skip, "SkipDistance");
   2266     to_skip = 0;
   2267   }
   2268   return to_skip;
   2269 }
   2270 
   2271 
   2272 BackReference Serializer::AllocateLargeObject(int size) {
   2273   // Large objects are allocated one-by-one when deserializing. We do not
   2274   // have to keep track of multiple chunks.
   2275   large_objects_total_size_ += size;
   2276   return BackReference::LargeObjectReference(seen_large_objects_index_++);
   2277 }
   2278 
   2279 
   2280 BackReference Serializer::Allocate(AllocationSpace space, int size) {
   2281   DCHECK(space >= 0 && space < kNumberOfPreallocatedSpaces);
   2282   DCHECK(size > 0 && size <= static_cast<int>(max_chunk_size(space)));
   2283   uint32_t new_chunk_size = pending_chunk_[space] + size;
   2284   if (new_chunk_size > max_chunk_size(space)) {
   2285     // The new chunk size would not fit onto a single page. Complete the
   2286     // current chunk and start a new one.
   2287     sink_->Put(kNextChunk, "NextChunk");
   2288     sink_->Put(space, "NextChunkSpace");
   2289     completed_chunks_[space].Add(pending_chunk_[space]);
   2290     DCHECK_LE(completed_chunks_[space].length(), BackReference::kMaxChunkIndex);
   2291     pending_chunk_[space] = 0;
   2292     new_chunk_size = size;
   2293   }
   2294   uint32_t offset = pending_chunk_[space];
   2295   pending_chunk_[space] = new_chunk_size;
   2296   return BackReference::Reference(space, completed_chunks_[space].length(),
   2297                                   offset);
   2298 }
   2299 
   2300 
   2301 void Serializer::Pad() {
   2302   // The non-branching GetInt will read up to 3 bytes too far, so we need
   2303   // to pad the snapshot to make sure we don't read over the end.
   2304   for (unsigned i = 0; i < sizeof(int32_t) - 1; i++) {
   2305     sink_->Put(kNop, "Padding");
   2306   }
   2307   // Pad up to pointer size for checksum.
   2308   while (!IsAligned(sink_->Position(), kPointerAlignment)) {
   2309     sink_->Put(kNop, "Padding");
   2310   }
   2311 }
   2312 
   2313 
   2314 void Serializer::InitializeCodeAddressMap() {
   2315   isolate_->InitializeLoggingAndCounters();
   2316   code_address_map_ = new CodeAddressMap(isolate_);
   2317 }
   2318 
   2319 
   2320 Code* Serializer::CopyCode(Code* code) {
   2321   code_buffer_.Rewind(0);  // Clear buffer without deleting backing store.
   2322   int size = code->CodeSize();
   2323   code_buffer_.AddAll(Vector<byte>(code->address(), size));
   2324   return Code::cast(HeapObject::FromAddress(&code_buffer_.first()));
   2325 }
   2326 
   2327 
   2328 ScriptData* CodeSerializer::Serialize(Isolate* isolate,
   2329                                       Handle<SharedFunctionInfo> info,
   2330                                       Handle<String> source) {
   2331   base::ElapsedTimer timer;
   2332   if (FLAG_profile_deserialization) timer.Start();
   2333   if (FLAG_trace_serializer) {
   2334     PrintF("[Serializing from");
   2335     Object* script = info->script();
   2336     if (script->IsScript()) Script::cast(script)->name()->ShortPrint();
   2337     PrintF("]\n");
   2338   }
   2339 
   2340   // Serialize code object.
   2341   SnapshotByteSink sink(info->code()->CodeSize() * 2);
   2342   CodeSerializer cs(isolate, &sink, *source);
   2343   DisallowHeapAllocation no_gc;
   2344   Object** location = Handle<Object>::cast(info).location();
   2345   cs.VisitPointer(location);
   2346   cs.SerializeDeferredObjects();
   2347   cs.Pad();
   2348 
   2349   SerializedCodeData data(sink.data(), cs);
   2350   ScriptData* script_data = data.GetScriptData();
   2351 
   2352   if (FLAG_profile_deserialization) {
   2353     double ms = timer.Elapsed().InMillisecondsF();
   2354     int length = script_data->length();
   2355     PrintF("[Serializing to %d bytes took %0.3f ms]\n", length, ms);
   2356   }
   2357 
   2358   return script_data;
   2359 }
   2360 
   2361 
   2362 void CodeSerializer::SerializeObject(HeapObject* obj, HowToCode how_to_code,
   2363                                      WhereToPoint where_to_point, int skip) {
   2364   int root_index = root_index_map_.Lookup(obj);
   2365   if (root_index != RootIndexMap::kInvalidRootIndex) {
   2366     PutRoot(root_index, obj, how_to_code, where_to_point, skip);
   2367     return;
   2368   }
   2369 
   2370   if (SerializeKnownObject(obj, how_to_code, where_to_point, skip)) return;
   2371 
   2372   FlushSkip(skip);
   2373 
   2374   if (obj->IsCode()) {
   2375     Code* code_object = Code::cast(obj);
   2376     switch (code_object->kind()) {
   2377       case Code::OPTIMIZED_FUNCTION:  // No optimized code compiled yet.
   2378       case Code::HANDLER:             // No handlers patched in yet.
   2379       case Code::REGEXP:              // No regexp literals initialized yet.
   2380       case Code::NUMBER_OF_KINDS:     // Pseudo enum value.
   2381         CHECK(false);
   2382       case Code::BUILTIN:
   2383         SerializeBuiltin(code_object->builtin_index(), how_to_code,
   2384                          where_to_point);
   2385         return;
   2386       case Code::STUB:
   2387         SerializeCodeStub(code_object->stub_key(), how_to_code, where_to_point);
   2388         return;
   2389 #define IC_KIND_CASE(KIND) case Code::KIND:
   2390         IC_KIND_LIST(IC_KIND_CASE)
   2391 #undef IC_KIND_CASE
   2392         SerializeIC(code_object, how_to_code, where_to_point);
   2393         return;
   2394       case Code::FUNCTION:
   2395         DCHECK(code_object->has_reloc_info_for_serialization());
   2396         SerializeGeneric(code_object, how_to_code, where_to_point);
   2397         return;
   2398       case Code::WASM_FUNCTION:
   2399         UNREACHABLE();
   2400     }
   2401     UNREACHABLE();
   2402   }
   2403 
   2404   // Past this point we should not see any (context-specific) maps anymore.
   2405   CHECK(!obj->IsMap());
   2406   // There should be no references to the global object embedded.
   2407   CHECK(!obj->IsJSGlobalProxy() && !obj->IsJSGlobalObject());
   2408   // There should be no hash table embedded. They would require rehashing.
   2409   CHECK(!obj->IsHashTable());
   2410   // We expect no instantiated function objects or contexts.
   2411   CHECK(!obj->IsJSFunction() && !obj->IsContext());
   2412 
   2413   SerializeGeneric(obj, how_to_code, where_to_point);
   2414 }
   2415 
   2416 
   2417 void CodeSerializer::SerializeGeneric(HeapObject* heap_object,
   2418                                       HowToCode how_to_code,
   2419                                       WhereToPoint where_to_point) {
   2420   // Object has not yet been serialized.  Serialize it here.
   2421   ObjectSerializer serializer(this, heap_object, sink_, how_to_code,
   2422                               where_to_point);
   2423   serializer.Serialize();
   2424 }
   2425 
   2426 
   2427 void CodeSerializer::SerializeBuiltin(int builtin_index, HowToCode how_to_code,
   2428                                       WhereToPoint where_to_point) {
   2429   DCHECK((how_to_code == kPlain && where_to_point == kStartOfObject) ||
   2430          (how_to_code == kPlain && where_to_point == kInnerPointer) ||
   2431          (how_to_code == kFromCode && where_to_point == kInnerPointer));
   2432   DCHECK_LT(builtin_index, Builtins::builtin_count);
   2433   DCHECK_LE(0, builtin_index);
   2434 
   2435   if (FLAG_trace_serializer) {
   2436     PrintF(" Encoding builtin: %s\n",
   2437            isolate()->builtins()->name(builtin_index));
   2438   }
   2439 
   2440   sink_->Put(kBuiltin + how_to_code + where_to_point, "Builtin");
   2441   sink_->PutInt(builtin_index, "builtin_index");
   2442 }
   2443 
   2444 
   2445 void CodeSerializer::SerializeCodeStub(uint32_t stub_key, HowToCode how_to_code,
   2446                                        WhereToPoint where_to_point) {
   2447   DCHECK((how_to_code == kPlain && where_to_point == kStartOfObject) ||
   2448          (how_to_code == kPlain && where_to_point == kInnerPointer) ||
   2449          (how_to_code == kFromCode && where_to_point == kInnerPointer));
   2450   DCHECK(CodeStub::MajorKeyFromKey(stub_key) != CodeStub::NoCache);
   2451   DCHECK(!CodeStub::GetCode(isolate(), stub_key).is_null());
   2452 
   2453   int index = AddCodeStubKey(stub_key) + kCodeStubsBaseIndex;
   2454 
   2455   if (FLAG_trace_serializer) {
   2456     PrintF(" Encoding code stub %s as %d\n",
   2457            CodeStub::MajorName(CodeStub::MajorKeyFromKey(stub_key)), index);
   2458   }
   2459 
   2460   sink_->Put(kAttachedReference + how_to_code + where_to_point, "CodeStub");
   2461   sink_->PutInt(index, "CodeStub key");
   2462 }
   2463 
   2464 
   2465 void CodeSerializer::SerializeIC(Code* ic, HowToCode how_to_code,
   2466                                  WhereToPoint where_to_point) {
   2467   // The IC may be implemented as a stub.
   2468   uint32_t stub_key = ic->stub_key();
   2469   if (stub_key != CodeStub::NoCacheKey()) {
   2470     if (FLAG_trace_serializer) {
   2471       PrintF(" %s is a code stub\n", Code::Kind2String(ic->kind()));
   2472     }
   2473     SerializeCodeStub(stub_key, how_to_code, where_to_point);
   2474     return;
   2475   }
   2476   // The IC may be implemented as builtin. Only real builtins have an
   2477   // actual builtin_index value attached (otherwise it's just garbage).
   2478   // Compare to make sure we are really dealing with a builtin.
   2479   int builtin_index = ic->builtin_index();
   2480   if (builtin_index < Builtins::builtin_count) {
   2481     Builtins::Name name = static_cast<Builtins::Name>(builtin_index);
   2482     Code* builtin = isolate()->builtins()->builtin(name);
   2483     if (builtin == ic) {
   2484       if (FLAG_trace_serializer) {
   2485         PrintF(" %s is a builtin\n", Code::Kind2String(ic->kind()));
   2486       }
   2487       DCHECK(ic->kind() == Code::KEYED_LOAD_IC ||
   2488              ic->kind() == Code::KEYED_STORE_IC);
   2489       SerializeBuiltin(builtin_index, how_to_code, where_to_point);
   2490       return;
   2491     }
   2492   }
   2493   // The IC may also just be a piece of code kept in the non_monomorphic_cache.
   2494   // In that case, just serialize as a normal code object.
   2495   if (FLAG_trace_serializer) {
   2496     PrintF(" %s has no special handling\n", Code::Kind2String(ic->kind()));
   2497   }
   2498   DCHECK(ic->kind() == Code::LOAD_IC || ic->kind() == Code::STORE_IC);
   2499   SerializeGeneric(ic, how_to_code, where_to_point);
   2500 }
   2501 
   2502 
   2503 int CodeSerializer::AddCodeStubKey(uint32_t stub_key) {
   2504   // TODO(yangguo) Maybe we need a hash table for a faster lookup than O(n^2).
   2505   int index = 0;
   2506   while (index < stub_keys_.length()) {
   2507     if (stub_keys_[index] == stub_key) return index;
   2508     index++;
   2509   }
   2510   stub_keys_.Add(stub_key);
   2511   return index;
   2512 }
   2513 
   2514 
   2515 MaybeHandle<SharedFunctionInfo> CodeSerializer::Deserialize(
   2516     Isolate* isolate, ScriptData* cached_data, Handle<String> source) {
   2517   base::ElapsedTimer timer;
   2518   if (FLAG_profile_deserialization) timer.Start();
   2519 
   2520   HandleScope scope(isolate);
   2521 
   2522   base::SmartPointer<SerializedCodeData> scd(
   2523       SerializedCodeData::FromCachedData(isolate, cached_data, *source));
   2524   if (scd.is_empty()) {
   2525     if (FLAG_profile_deserialization) PrintF("[Cached code failed check]\n");
   2526     DCHECK(cached_data->rejected());
   2527     return MaybeHandle<SharedFunctionInfo>();
   2528   }
   2529 
   2530   // Prepare and register list of attached objects.
   2531   Vector<const uint32_t> code_stub_keys = scd->CodeStubKeys();
   2532   Vector<Handle<Object> > attached_objects = Vector<Handle<Object> >::New(
   2533       code_stub_keys.length() + kCodeStubsBaseIndex);
   2534   attached_objects[kSourceObjectIndex] = source;
   2535   for (int i = 0; i < code_stub_keys.length(); i++) {
   2536     attached_objects[i + kCodeStubsBaseIndex] =
   2537         CodeStub::GetCode(isolate, code_stub_keys[i]).ToHandleChecked();
   2538   }
   2539 
   2540   Deserializer deserializer(scd.get());
   2541   deserializer.SetAttachedObjects(attached_objects);
   2542 
   2543   // Deserialize.
   2544   Handle<SharedFunctionInfo> result;
   2545   if (!deserializer.DeserializeCode(isolate).ToHandle(&result)) {
   2546     // Deserializing may fail if the reservations cannot be fulfilled.
   2547     if (FLAG_profile_deserialization) PrintF("[Deserializing failed]\n");
   2548     return MaybeHandle<SharedFunctionInfo>();
   2549   }
   2550 
   2551   if (FLAG_profile_deserialization) {
   2552     double ms = timer.Elapsed().InMillisecondsF();
   2553     int length = cached_data->length();
   2554     PrintF("[Deserializing from %d bytes took %0.3f ms]\n", length, ms);
   2555   }
   2556   result->set_deserialized(true);
   2557 
   2558   if (isolate->logger()->is_logging_code_events() ||
   2559       isolate->cpu_profiler()->is_profiling()) {
   2560     String* name = isolate->heap()->empty_string();
   2561     if (result->script()->IsScript()) {
   2562       Script* script = Script::cast(result->script());
   2563       if (script->name()->IsString()) name = String::cast(script->name());
   2564     }
   2565     isolate->logger()->CodeCreateEvent(Logger::SCRIPT_TAG, result->code(),
   2566                                        *result, NULL, name);
   2567   }
   2568   return scope.CloseAndEscape(result);
   2569 }
   2570 
   2571 
   2572 void SerializedData::AllocateData(int size) {
   2573   DCHECK(!owns_data_);
   2574   data_ = NewArray<byte>(size);
   2575   size_ = size;
   2576   owns_data_ = true;
   2577   DCHECK(IsAligned(reinterpret_cast<intptr_t>(data_), kPointerAlignment));
   2578 }
   2579 
   2580 
   2581 SnapshotData::SnapshotData(const Serializer& ser) {
   2582   DisallowHeapAllocation no_gc;
   2583   List<Reservation> reservations;
   2584   ser.EncodeReservations(&reservations);
   2585   const List<byte>& payload = ser.sink()->data();
   2586 
   2587   // Calculate sizes.
   2588   int reservation_size = reservations.length() * kInt32Size;
   2589   int size = kHeaderSize + reservation_size + payload.length();
   2590 
   2591   // Allocate backing store and create result data.
   2592   AllocateData(size);
   2593 
   2594   // Set header values.
   2595   SetMagicNumber(ser.isolate());
   2596   SetHeaderValue(kCheckSumOffset, Version::Hash());
   2597   SetHeaderValue(kNumReservationsOffset, reservations.length());
   2598   SetHeaderValue(kPayloadLengthOffset, payload.length());
   2599 
   2600   // Copy reservation chunk sizes.
   2601   CopyBytes(data_ + kHeaderSize, reinterpret_cast<byte*>(reservations.begin()),
   2602             reservation_size);
   2603 
   2604   // Copy serialized data.
   2605   CopyBytes(data_ + kHeaderSize + reservation_size, payload.begin(),
   2606             static_cast<size_t>(payload.length()));
   2607 }
   2608 
   2609 
   2610 bool SnapshotData::IsSane() {
   2611   return GetHeaderValue(kCheckSumOffset) == Version::Hash();
   2612 }
   2613 
   2614 
   2615 Vector<const SerializedData::Reservation> SnapshotData::Reservations() const {
   2616   return Vector<const Reservation>(
   2617       reinterpret_cast<const Reservation*>(data_ + kHeaderSize),
   2618       GetHeaderValue(kNumReservationsOffset));
   2619 }
   2620 
   2621 
   2622 Vector<const byte> SnapshotData::Payload() const {
   2623   int reservations_size = GetHeaderValue(kNumReservationsOffset) * kInt32Size;
   2624   const byte* payload = data_ + kHeaderSize + reservations_size;
   2625   int length = GetHeaderValue(kPayloadLengthOffset);
   2626   DCHECK_EQ(data_ + size_, payload + length);
   2627   return Vector<const byte>(payload, length);
   2628 }
   2629 
   2630 
   2631 class Checksum {
   2632  public:
   2633   explicit Checksum(Vector<const byte> payload) {
   2634 #ifdef MEMORY_SANITIZER
   2635     // Computing the checksum includes padding bytes for objects like strings.
   2636     // Mark every object as initialized in the code serializer.
   2637     MSAN_MEMORY_IS_INITIALIZED(payload.start(), payload.length());
   2638 #endif  // MEMORY_SANITIZER
   2639     // Fletcher's checksum. Modified to reduce 64-bit sums to 32-bit.
   2640     uintptr_t a = 1;
   2641     uintptr_t b = 0;
   2642     const uintptr_t* cur = reinterpret_cast<const uintptr_t*>(payload.start());
   2643     DCHECK(IsAligned(payload.length(), kIntptrSize));
   2644     const uintptr_t* end = cur + payload.length() / kIntptrSize;
   2645     while (cur < end) {
   2646       // Unsigned overflow expected and intended.
   2647       a += *cur++;
   2648       b += a;
   2649     }
   2650 #if V8_HOST_ARCH_64_BIT
   2651     a ^= a >> 32;
   2652     b ^= b >> 32;
   2653 #endif  // V8_HOST_ARCH_64_BIT
   2654     a_ = static_cast<uint32_t>(a);
   2655     b_ = static_cast<uint32_t>(b);
   2656   }
   2657 
   2658   bool Check(uint32_t a, uint32_t b) const { return a == a_ && b == b_; }
   2659 
   2660   uint32_t a() const { return a_; }
   2661   uint32_t b() const { return b_; }
   2662 
   2663  private:
   2664   uint32_t a_;
   2665   uint32_t b_;
   2666 
   2667   DISALLOW_COPY_AND_ASSIGN(Checksum);
   2668 };
   2669 
   2670 
   2671 SerializedCodeData::SerializedCodeData(const List<byte>& payload,
   2672                                        const CodeSerializer& cs) {
   2673   DisallowHeapAllocation no_gc;
   2674   const List<uint32_t>* stub_keys = cs.stub_keys();
   2675 
   2676   List<Reservation> reservations;
   2677   cs.EncodeReservations(&reservations);
   2678 
   2679   // Calculate sizes.
   2680   int reservation_size = reservations.length() * kInt32Size;
   2681   int num_stub_keys = stub_keys->length();
   2682   int stub_keys_size = stub_keys->length() * kInt32Size;
   2683   int payload_offset = kHeaderSize + reservation_size + stub_keys_size;
   2684   int padded_payload_offset = POINTER_SIZE_ALIGN(payload_offset);
   2685   int size = padded_payload_offset + payload.length();
   2686 
   2687   // Allocate backing store and create result data.
   2688   AllocateData(size);
   2689 
   2690   // Set header values.
   2691   SetMagicNumber(cs.isolate());
   2692   SetHeaderValue(kVersionHashOffset, Version::Hash());
   2693   SetHeaderValue(kSourceHashOffset, SourceHash(cs.source()));
   2694   SetHeaderValue(kCpuFeaturesOffset,
   2695                  static_cast<uint32_t>(CpuFeatures::SupportedFeatures()));
   2696   SetHeaderValue(kFlagHashOffset, FlagList::Hash());
   2697   SetHeaderValue(kNumReservationsOffset, reservations.length());
   2698   SetHeaderValue(kNumCodeStubKeysOffset, num_stub_keys);
   2699   SetHeaderValue(kPayloadLengthOffset, payload.length());
   2700 
   2701   Checksum checksum(payload.ToConstVector());
   2702   SetHeaderValue(kChecksum1Offset, checksum.a());
   2703   SetHeaderValue(kChecksum2Offset, checksum.b());
   2704 
   2705   // Copy reservation chunk sizes.
   2706   CopyBytes(data_ + kHeaderSize, reinterpret_cast<byte*>(reservations.begin()),
   2707             reservation_size);
   2708 
   2709   // Copy code stub keys.
   2710   CopyBytes(data_ + kHeaderSize + reservation_size,
   2711             reinterpret_cast<byte*>(stub_keys->begin()), stub_keys_size);
   2712 
   2713   memset(data_ + payload_offset, 0, padded_payload_offset - payload_offset);
   2714 
   2715   // Copy serialized data.
   2716   CopyBytes(data_ + padded_payload_offset, payload.begin(),
   2717             static_cast<size_t>(payload.length()));
   2718 }
   2719 
   2720 
   2721 SerializedCodeData::SanityCheckResult SerializedCodeData::SanityCheck(
   2722     Isolate* isolate, String* source) const {
   2723   uint32_t magic_number = GetMagicNumber();
   2724   if (magic_number != ComputeMagicNumber(isolate)) return MAGIC_NUMBER_MISMATCH;
   2725   uint32_t version_hash = GetHeaderValue(kVersionHashOffset);
   2726   uint32_t source_hash = GetHeaderValue(kSourceHashOffset);
   2727   uint32_t cpu_features = GetHeaderValue(kCpuFeaturesOffset);
   2728   uint32_t flags_hash = GetHeaderValue(kFlagHashOffset);
   2729   uint32_t c1 = GetHeaderValue(kChecksum1Offset);
   2730   uint32_t c2 = GetHeaderValue(kChecksum2Offset);
   2731   if (version_hash != Version::Hash()) return VERSION_MISMATCH;
   2732   if (source_hash != SourceHash(source)) return SOURCE_MISMATCH;
   2733   if (cpu_features != static_cast<uint32_t>(CpuFeatures::SupportedFeatures())) {
   2734     return CPU_FEATURES_MISMATCH;
   2735   }
   2736   if (flags_hash != FlagList::Hash()) return FLAGS_MISMATCH;
   2737   if (!Checksum(Payload()).Check(c1, c2)) return CHECKSUM_MISMATCH;
   2738   return CHECK_SUCCESS;
   2739 }
   2740 
   2741 
   2742 uint32_t SerializedCodeData::SourceHash(String* source) const {
   2743   return source->length();
   2744 }
   2745 
   2746 
   2747 // Return ScriptData object and relinquish ownership over it to the caller.
   2748 ScriptData* SerializedCodeData::GetScriptData() {
   2749   DCHECK(owns_data_);
   2750   ScriptData* result = new ScriptData(data_, size_);
   2751   result->AcquireDataOwnership();
   2752   owns_data_ = false;
   2753   data_ = NULL;
   2754   return result;
   2755 }
   2756 
   2757 
   2758 Vector<const SerializedData::Reservation> SerializedCodeData::Reservations()
   2759     const {
   2760   return Vector<const Reservation>(
   2761       reinterpret_cast<const Reservation*>(data_ + kHeaderSize),
   2762       GetHeaderValue(kNumReservationsOffset));
   2763 }
   2764 
   2765 
   2766 Vector<const byte> SerializedCodeData::Payload() const {
   2767   int reservations_size = GetHeaderValue(kNumReservationsOffset) * kInt32Size;
   2768   int code_stubs_size = GetHeaderValue(kNumCodeStubKeysOffset) * kInt32Size;
   2769   int payload_offset = kHeaderSize + reservations_size + code_stubs_size;
   2770   int padded_payload_offset = POINTER_SIZE_ALIGN(payload_offset);
   2771   const byte* payload = data_ + padded_payload_offset;
   2772   DCHECK(IsAligned(reinterpret_cast<intptr_t>(payload), kPointerAlignment));
   2773   int length = GetHeaderValue(kPayloadLengthOffset);
   2774   DCHECK_EQ(data_ + size_, payload + length);
   2775   return Vector<const byte>(payload, length);
   2776 }
   2777 
   2778 
   2779 Vector<const uint32_t> SerializedCodeData::CodeStubKeys() const {
   2780   int reservations_size = GetHeaderValue(kNumReservationsOffset) * kInt32Size;
   2781   const byte* start = data_ + kHeaderSize + reservations_size;
   2782   return Vector<const uint32_t>(reinterpret_cast<const uint32_t*>(start),
   2783                                 GetHeaderValue(kNumCodeStubKeysOffset));
   2784 }
   2785 
   2786 
   2787 SerializedCodeData::SerializedCodeData(ScriptData* data)
   2788     : SerializedData(const_cast<byte*>(data->data()), data->length()) {}
   2789 
   2790 
   2791 SerializedCodeData* SerializedCodeData::FromCachedData(Isolate* isolate,
   2792                                                        ScriptData* cached_data,
   2793                                                        String* source) {
   2794   DisallowHeapAllocation no_gc;
   2795   SerializedCodeData* scd = new SerializedCodeData(cached_data);
   2796   SanityCheckResult r = scd->SanityCheck(isolate, source);
   2797   if (r == CHECK_SUCCESS) return scd;
   2798   cached_data->Reject();
   2799   source->GetIsolate()->counters()->code_cache_reject_reason()->AddSample(r);
   2800   delete scd;
   2801   return NULL;
   2802 }
   2803 }  // namespace internal
   2804 }  // namespace v8
   2805