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