blob: 06c6df724c0d01e5189f60cdb49000dc269cd22c [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "accessors.h"
31#include "api.h"
32#include "execution.h"
33#include "global-handles.h"
34#include "ic-inl.h"
35#include "natives.h"
36#include "platform.h"
37#include "runtime.h"
38#include "serialize.h"
39#include "stub-cache.h"
40#include "v8threads.h"
Steve Block3ce2e202009-11-05 08:53:23 +000041#include "top.h"
Steve Blockd0582a62009-12-15 09:54:21 +000042#include "bootstrapper.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000043
44namespace v8 {
45namespace internal {
46
Steve Blocka7e24c12009-10-30 11:49:00 +000047
48// -----------------------------------------------------------------------------
49// Coding of external references.
50
51// The encoding of an external reference. The type is in the high word.
52// The id is in the low word.
53static uint32_t EncodeExternal(TypeCode type, uint16_t id) {
54 return static_cast<uint32_t>(type) << 16 | id;
55}
56
57
58static int* GetInternalPointer(StatsCounter* counter) {
59 // All counters refer to dummy_counter, if deserializing happens without
60 // setting up counters.
61 static int dummy_counter = 0;
62 return counter->Enabled() ? counter->GetInternalPointer() : &dummy_counter;
63}
64
65
66// ExternalReferenceTable is a helper class that defines the relationship
67// between external references and their encodings. It is used to build
68// hashmaps in ExternalReferenceEncoder and ExternalReferenceDecoder.
69class ExternalReferenceTable {
70 public:
71 static ExternalReferenceTable* instance() {
72 if (!instance_) instance_ = new ExternalReferenceTable();
73 return instance_;
74 }
75
76 int size() const { return refs_.length(); }
77
78 Address address(int i) { return refs_[i].address; }
79
80 uint32_t code(int i) { return refs_[i].code; }
81
82 const char* name(int i) { return refs_[i].name; }
83
84 int max_id(int code) { return max_id_[code]; }
85
86 private:
87 static ExternalReferenceTable* instance_;
88
89 ExternalReferenceTable() : refs_(64) { PopulateTable(); }
90 ~ExternalReferenceTable() { }
91
92 struct ExternalReferenceEntry {
93 Address address;
94 uint32_t code;
95 const char* name;
96 };
97
98 void PopulateTable();
99
100 // For a few types of references, we can get their address from their id.
101 void AddFromId(TypeCode type, uint16_t id, const char* name);
102
103 // For other types of references, the caller will figure out the address.
104 void Add(Address address, TypeCode type, uint16_t id, const char* name);
105
106 List<ExternalReferenceEntry> refs_;
107 int max_id_[kTypeCodeCount];
108};
109
110
111ExternalReferenceTable* ExternalReferenceTable::instance_ = NULL;
112
113
114void ExternalReferenceTable::AddFromId(TypeCode type,
115 uint16_t id,
116 const char* name) {
117 Address address;
118 switch (type) {
119 case C_BUILTIN: {
120 ExternalReference ref(static_cast<Builtins::CFunctionId>(id));
121 address = ref.address();
122 break;
123 }
124 case BUILTIN: {
125 ExternalReference ref(static_cast<Builtins::Name>(id));
126 address = ref.address();
127 break;
128 }
129 case RUNTIME_FUNCTION: {
130 ExternalReference ref(static_cast<Runtime::FunctionId>(id));
131 address = ref.address();
132 break;
133 }
134 case IC_UTILITY: {
135 ExternalReference ref(IC_Utility(static_cast<IC::UtilityId>(id)));
136 address = ref.address();
137 break;
138 }
139 default:
140 UNREACHABLE();
141 return;
142 }
143 Add(address, type, id, name);
144}
145
146
147void ExternalReferenceTable::Add(Address address,
148 TypeCode type,
149 uint16_t id,
150 const char* name) {
Steve Blockd0582a62009-12-15 09:54:21 +0000151 ASSERT_NE(NULL, address);
Steve Blocka7e24c12009-10-30 11:49:00 +0000152 ExternalReferenceEntry entry;
153 entry.address = address;
154 entry.code = EncodeExternal(type, id);
155 entry.name = name;
Steve Blockd0582a62009-12-15 09:54:21 +0000156 ASSERT_NE(0, entry.code);
Steve Blocka7e24c12009-10-30 11:49:00 +0000157 refs_.Add(entry);
158 if (id > max_id_[type]) max_id_[type] = id;
159}
160
161
162void ExternalReferenceTable::PopulateTable() {
163 for (int type_code = 0; type_code < kTypeCodeCount; type_code++) {
164 max_id_[type_code] = 0;
165 }
166
167 // The following populates all of the different type of external references
168 // into the ExternalReferenceTable.
169 //
170 // NOTE: This function was originally 100k of code. It has since been
171 // rewritten to be mostly table driven, as the callback macro style tends to
172 // very easily cause code bloat. Please be careful in the future when adding
173 // new references.
174
175 struct RefTableEntry {
176 TypeCode type;
177 uint16_t id;
178 const char* name;
179 };
180
181 static const RefTableEntry ref_table[] = {
182 // Builtins
Leon Clarkee46be812010-01-19 14:06:41 +0000183#define DEF_ENTRY_C(name, ignored) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000184 { C_BUILTIN, \
185 Builtins::c_##name, \
186 "Builtins::" #name },
187
188 BUILTIN_LIST_C(DEF_ENTRY_C)
189#undef DEF_ENTRY_C
190
Leon Clarkee46be812010-01-19 14:06:41 +0000191#define DEF_ENTRY_C(name, ignored) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000192 { BUILTIN, \
193 Builtins::name, \
194 "Builtins::" #name },
Leon Clarkee46be812010-01-19 14:06:41 +0000195#define DEF_ENTRY_A(name, kind, state) DEF_ENTRY_C(name, ignored)
Steve Blocka7e24c12009-10-30 11:49:00 +0000196
197 BUILTIN_LIST_C(DEF_ENTRY_C)
198 BUILTIN_LIST_A(DEF_ENTRY_A)
199 BUILTIN_LIST_DEBUG_A(DEF_ENTRY_A)
200#undef DEF_ENTRY_C
201#undef DEF_ENTRY_A
202
203 // Runtime functions
204#define RUNTIME_ENTRY(name, nargs, ressize) \
205 { RUNTIME_FUNCTION, \
206 Runtime::k##name, \
207 "Runtime::" #name },
208
209 RUNTIME_FUNCTION_LIST(RUNTIME_ENTRY)
210#undef RUNTIME_ENTRY
211
212 // IC utilities
213#define IC_ENTRY(name) \
214 { IC_UTILITY, \
215 IC::k##name, \
216 "IC::" #name },
217
218 IC_UTIL_LIST(IC_ENTRY)
219#undef IC_ENTRY
220 }; // end of ref_table[].
221
222 for (size_t i = 0; i < ARRAY_SIZE(ref_table); ++i) {
223 AddFromId(ref_table[i].type, ref_table[i].id, ref_table[i].name);
224 }
225
226#ifdef ENABLE_DEBUGGER_SUPPORT
227 // Debug addresses
228 Add(Debug_Address(Debug::k_after_break_target_address).address(),
229 DEBUG_ADDRESS,
230 Debug::k_after_break_target_address << kDebugIdShift,
231 "Debug::after_break_target_address()");
232 Add(Debug_Address(Debug::k_debug_break_return_address).address(),
233 DEBUG_ADDRESS,
234 Debug::k_debug_break_return_address << kDebugIdShift,
235 "Debug::debug_break_return_address()");
236 const char* debug_register_format = "Debug::register_address(%i)";
Steve Blockd0582a62009-12-15 09:54:21 +0000237 int dr_format_length = StrLength(debug_register_format);
Steve Blocka7e24c12009-10-30 11:49:00 +0000238 for (int i = 0; i < kNumJSCallerSaved; ++i) {
239 Vector<char> name = Vector<char>::New(dr_format_length + 1);
240 OS::SNPrintF(name, debug_register_format, i);
241 Add(Debug_Address(Debug::k_register_address, i).address(),
242 DEBUG_ADDRESS,
243 Debug::k_register_address << kDebugIdShift | i,
244 name.start());
245 }
246#endif
247
248 // Stat counters
249 struct StatsRefTableEntry {
250 StatsCounter* counter;
251 uint16_t id;
252 const char* name;
253 };
254
255 static const StatsRefTableEntry stats_ref_table[] = {
256#define COUNTER_ENTRY(name, caption) \
257 { &Counters::name, \
258 Counters::k_##name, \
259 "Counters::" #name },
260
261 STATS_COUNTER_LIST_1(COUNTER_ENTRY)
262 STATS_COUNTER_LIST_2(COUNTER_ENTRY)
263#undef COUNTER_ENTRY
264 }; // end of stats_ref_table[].
265
266 for (size_t i = 0; i < ARRAY_SIZE(stats_ref_table); ++i) {
267 Add(reinterpret_cast<Address>(
268 GetInternalPointer(stats_ref_table[i].counter)),
269 STATS_COUNTER,
270 stats_ref_table[i].id,
271 stats_ref_table[i].name);
272 }
273
274 // Top addresses
Steve Block3ce2e202009-11-05 08:53:23 +0000275 const char* top_address_format = "Top::%s";
276
277 const char* AddressNames[] = {
278#define C(name) #name,
279 TOP_ADDRESS_LIST(C)
280 TOP_ADDRESS_LIST_PROF(C)
281 NULL
282#undef C
283 };
284
Steve Blockd0582a62009-12-15 09:54:21 +0000285 int top_format_length = StrLength(top_address_format) - 2;
Steve Blocka7e24c12009-10-30 11:49:00 +0000286 for (uint16_t i = 0; i < Top::k_top_address_count; ++i) {
Steve Block3ce2e202009-11-05 08:53:23 +0000287 const char* address_name = AddressNames[i];
288 Vector<char> name =
Steve Blockd0582a62009-12-15 09:54:21 +0000289 Vector<char>::New(top_format_length + StrLength(address_name) + 1);
Steve Blocka7e24c12009-10-30 11:49:00 +0000290 const char* chars = name.start();
Steve Block3ce2e202009-11-05 08:53:23 +0000291 OS::SNPrintF(name, top_address_format, address_name);
Steve Blocka7e24c12009-10-30 11:49:00 +0000292 Add(Top::get_address_from_id((Top::AddressId)i), TOP_ADDRESS, i, chars);
293 }
294
295 // Extensions
296 Add(FUNCTION_ADDR(GCExtension::GC), EXTENSION, 1,
297 "GCExtension::GC");
298
299 // Accessors
300#define ACCESSOR_DESCRIPTOR_DECLARATION(name) \
301 Add((Address)&Accessors::name, \
302 ACCESSOR, \
303 Accessors::k##name, \
304 "Accessors::" #name);
305
306 ACCESSOR_DESCRIPTOR_LIST(ACCESSOR_DESCRIPTOR_DECLARATION)
307#undef ACCESSOR_DESCRIPTOR_DECLARATION
308
309 // Stub cache tables
310 Add(SCTableReference::keyReference(StubCache::kPrimary).address(),
311 STUB_CACHE_TABLE,
312 1,
313 "StubCache::primary_->key");
314 Add(SCTableReference::valueReference(StubCache::kPrimary).address(),
315 STUB_CACHE_TABLE,
316 2,
317 "StubCache::primary_->value");
318 Add(SCTableReference::keyReference(StubCache::kSecondary).address(),
319 STUB_CACHE_TABLE,
320 3,
321 "StubCache::secondary_->key");
322 Add(SCTableReference::valueReference(StubCache::kSecondary).address(),
323 STUB_CACHE_TABLE,
324 4,
325 "StubCache::secondary_->value");
326
327 // Runtime entries
328 Add(ExternalReference::perform_gc_function().address(),
329 RUNTIME_ENTRY,
330 1,
331 "Runtime::PerformGC");
Steve Block6ded16b2010-05-10 14:33:55 +0100332 Add(ExternalReference::fill_heap_number_with_random_function().address(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000333 RUNTIME_ENTRY,
334 2,
Steve Block6ded16b2010-05-10 14:33:55 +0100335 "V8::FillHeapNumberWithRandom");
336
337 Add(ExternalReference::random_uint32_function().address(),
338 RUNTIME_ENTRY,
339 3,
340 "V8::Random");
Steve Blocka7e24c12009-10-30 11:49:00 +0000341
342 // Miscellaneous
Steve Blocka7e24c12009-10-30 11:49:00 +0000343 Add(ExternalReference::the_hole_value_location().address(),
344 UNCLASSIFIED,
345 2,
346 "Factory::the_hole_value().location()");
347 Add(ExternalReference::roots_address().address(),
348 UNCLASSIFIED,
349 3,
350 "Heap::roots_address()");
Steve Blockd0582a62009-12-15 09:54:21 +0000351 Add(ExternalReference::address_of_stack_limit().address(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000352 UNCLASSIFIED,
353 4,
354 "StackGuard::address_of_jslimit()");
Steve Blockd0582a62009-12-15 09:54:21 +0000355 Add(ExternalReference::address_of_real_stack_limit().address(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000356 UNCLASSIFIED,
357 5,
Steve Blockd0582a62009-12-15 09:54:21 +0000358 "StackGuard::address_of_real_jslimit()");
359 Add(ExternalReference::address_of_regexp_stack_limit().address(),
360 UNCLASSIFIED,
361 6,
Steve Blocka7e24c12009-10-30 11:49:00 +0000362 "RegExpStack::limit_address()");
363 Add(ExternalReference::new_space_start().address(),
364 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000365 7,
Steve Blocka7e24c12009-10-30 11:49:00 +0000366 "Heap::NewSpaceStart()");
Andrei Popescu402d9372010-02-26 13:31:12 +0000367 Add(ExternalReference::new_space_mask().address(),
Steve Blocka7e24c12009-10-30 11:49:00 +0000368 UNCLASSIFIED,
Steve Blockd0582a62009-12-15 09:54:21 +0000369 8,
Andrei Popescu402d9372010-02-26 13:31:12 +0000370 "Heap::NewSpaceMask()");
371 Add(ExternalReference::heap_always_allocate_scope_depth().address(),
372 UNCLASSIFIED,
373 9,
Steve Blocka7e24c12009-10-30 11:49:00 +0000374 "Heap::always_allocate_scope_depth()");
375 Add(ExternalReference::new_space_allocation_limit_address().address(),
376 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000377 10,
Steve Blocka7e24c12009-10-30 11:49:00 +0000378 "Heap::NewSpaceAllocationLimitAddress()");
379 Add(ExternalReference::new_space_allocation_top_address().address(),
380 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000381 11,
Steve Blocka7e24c12009-10-30 11:49:00 +0000382 "Heap::NewSpaceAllocationTopAddress()");
383#ifdef ENABLE_DEBUGGER_SUPPORT
384 Add(ExternalReference::debug_break().address(),
385 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000386 12,
Steve Blocka7e24c12009-10-30 11:49:00 +0000387 "Debug::Break()");
388 Add(ExternalReference::debug_step_in_fp_address().address(),
389 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000390 13,
Steve Blocka7e24c12009-10-30 11:49:00 +0000391 "Debug::step_in_fp_addr()");
392#endif
393 Add(ExternalReference::double_fp_operation(Token::ADD).address(),
394 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000395 14,
Steve Blocka7e24c12009-10-30 11:49:00 +0000396 "add_two_doubles");
397 Add(ExternalReference::double_fp_operation(Token::SUB).address(),
398 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000399 15,
Steve Blocka7e24c12009-10-30 11:49:00 +0000400 "sub_two_doubles");
401 Add(ExternalReference::double_fp_operation(Token::MUL).address(),
402 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000403 16,
Steve Blocka7e24c12009-10-30 11:49:00 +0000404 "mul_two_doubles");
405 Add(ExternalReference::double_fp_operation(Token::DIV).address(),
406 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000407 17,
Steve Blocka7e24c12009-10-30 11:49:00 +0000408 "div_two_doubles");
409 Add(ExternalReference::double_fp_operation(Token::MOD).address(),
410 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000411 18,
Steve Blocka7e24c12009-10-30 11:49:00 +0000412 "mod_two_doubles");
413 Add(ExternalReference::compare_doubles().address(),
414 UNCLASSIFIED,
Andrei Popescu402d9372010-02-26 13:31:12 +0000415 19,
Steve Blocka7e24c12009-10-30 11:49:00 +0000416 "compare_doubles");
Steve Block6ded16b2010-05-10 14:33:55 +0100417#ifndef V8_INTERPRETED_REGEXP
418 Add(ExternalReference::re_case_insensitive_compare_uc16().address(),
419 UNCLASSIFIED,
Kristian Monsen25f61362010-05-21 11:50:48 +0100420 20,
Steve Blocka7e24c12009-10-30 11:49:00 +0000421 "NativeRegExpMacroAssembler::CaseInsensitiveCompareUC16()");
422 Add(ExternalReference::re_check_stack_guard_state().address(),
423 UNCLASSIFIED,
Kristian Monsen25f61362010-05-21 11:50:48 +0100424 21,
Steve Blocka7e24c12009-10-30 11:49:00 +0000425 "RegExpMacroAssembler*::CheckStackGuardState()");
426 Add(ExternalReference::re_grow_stack().address(),
427 UNCLASSIFIED,
Kristian Monsen25f61362010-05-21 11:50:48 +0100428 22,
Steve Blocka7e24c12009-10-30 11:49:00 +0000429 "NativeRegExpMacroAssembler::GrowStack()");
Leon Clarkee46be812010-01-19 14:06:41 +0000430 Add(ExternalReference::re_word_character_map().address(),
431 UNCLASSIFIED,
Kristian Monsen25f61362010-05-21 11:50:48 +0100432 23,
Leon Clarkee46be812010-01-19 14:06:41 +0000433 "NativeRegExpMacroAssembler::word_character_map");
Steve Block6ded16b2010-05-10 14:33:55 +0100434#endif // V8_INTERPRETED_REGEXP
Leon Clarkee46be812010-01-19 14:06:41 +0000435 // Keyed lookup cache.
436 Add(ExternalReference::keyed_lookup_cache_keys().address(),
437 UNCLASSIFIED,
Kristian Monsen25f61362010-05-21 11:50:48 +0100438 24,
Leon Clarkee46be812010-01-19 14:06:41 +0000439 "KeyedLookupCache::keys()");
440 Add(ExternalReference::keyed_lookup_cache_field_offsets().address(),
441 UNCLASSIFIED,
Kristian Monsen25f61362010-05-21 11:50:48 +0100442 25,
Leon Clarkee46be812010-01-19 14:06:41 +0000443 "KeyedLookupCache::field_offsets()");
Andrei Popescu402d9372010-02-26 13:31:12 +0000444 Add(ExternalReference::transcendental_cache_array_address().address(),
445 UNCLASSIFIED,
Kristian Monsen25f61362010-05-21 11:50:48 +0100446 26,
Andrei Popescu402d9372010-02-26 13:31:12 +0000447 "TranscendentalCache::caches()");
Steve Blocka7e24c12009-10-30 11:49:00 +0000448}
449
450
451ExternalReferenceEncoder::ExternalReferenceEncoder()
452 : encodings_(Match) {
453 ExternalReferenceTable* external_references =
454 ExternalReferenceTable::instance();
455 for (int i = 0; i < external_references->size(); ++i) {
456 Put(external_references->address(i), i);
457 }
458}
459
460
461uint32_t ExternalReferenceEncoder::Encode(Address key) const {
462 int index = IndexOf(key);
463 return index >=0 ? ExternalReferenceTable::instance()->code(index) : 0;
464}
465
466
467const char* ExternalReferenceEncoder::NameOfAddress(Address key) const {
468 int index = IndexOf(key);
469 return index >=0 ? ExternalReferenceTable::instance()->name(index) : NULL;
470}
471
472
473int ExternalReferenceEncoder::IndexOf(Address key) const {
474 if (key == NULL) return -1;
475 HashMap::Entry* entry =
476 const_cast<HashMap &>(encodings_).Lookup(key, Hash(key), false);
477 return entry == NULL
478 ? -1
479 : static_cast<int>(reinterpret_cast<intptr_t>(entry->value));
480}
481
482
483void ExternalReferenceEncoder::Put(Address key, int index) {
484 HashMap::Entry* entry = encodings_.Lookup(key, Hash(key), true);
Steve Block6ded16b2010-05-10 14:33:55 +0100485 entry->value = reinterpret_cast<void*>(index);
Steve Blocka7e24c12009-10-30 11:49:00 +0000486}
487
488
489ExternalReferenceDecoder::ExternalReferenceDecoder()
490 : encodings_(NewArray<Address*>(kTypeCodeCount)) {
491 ExternalReferenceTable* external_references =
492 ExternalReferenceTable::instance();
493 for (int type = kFirstTypeCode; type < kTypeCodeCount; ++type) {
494 int max = external_references->max_id(type) + 1;
495 encodings_[type] = NewArray<Address>(max + 1);
496 }
497 for (int i = 0; i < external_references->size(); ++i) {
498 Put(external_references->code(i), external_references->address(i));
499 }
500}
501
502
503ExternalReferenceDecoder::~ExternalReferenceDecoder() {
504 for (int type = kFirstTypeCode; type < kTypeCodeCount; ++type) {
505 DeleteArray(encodings_[type]);
506 }
507 DeleteArray(encodings_);
508}
509
510
Steve Blocka7e24c12009-10-30 11:49:00 +0000511bool Serializer::serialization_enabled_ = false;
Steve Blockd0582a62009-12-15 09:54:21 +0000512bool Serializer::too_late_to_enable_now_ = false;
Leon Clarkee46be812010-01-19 14:06:41 +0000513ExternalReferenceDecoder* Deserializer::external_reference_decoder_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000514
515
Leon Clarkee46be812010-01-19 14:06:41 +0000516Deserializer::Deserializer(SnapshotByteSource* source) : source_(source) {
Steve Blockd0582a62009-12-15 09:54:21 +0000517}
518
519
520// This routine both allocates a new object, and also keeps
521// track of where objects have been allocated so that we can
522// fix back references when deserializing.
523Address Deserializer::Allocate(int space_index, Space* space, int size) {
524 Address address;
525 if (!SpaceIsLarge(space_index)) {
526 ASSERT(!SpaceIsPaged(space_index) ||
527 size <= Page::kPageSize - Page::kObjectStartOffset);
528 Object* new_allocation;
529 if (space_index == NEW_SPACE) {
530 new_allocation = reinterpret_cast<NewSpace*>(space)->AllocateRaw(size);
531 } else {
532 new_allocation = reinterpret_cast<PagedSpace*>(space)->AllocateRaw(size);
533 }
534 HeapObject* new_object = HeapObject::cast(new_allocation);
535 ASSERT(!new_object->IsFailure());
536 address = new_object->address();
537 high_water_[space_index] = address + size;
538 } else {
539 ASSERT(SpaceIsLarge(space_index));
540 ASSERT(size > Page::kPageSize - Page::kObjectStartOffset);
541 LargeObjectSpace* lo_space = reinterpret_cast<LargeObjectSpace*>(space);
542 Object* new_allocation;
543 if (space_index == kLargeData) {
544 new_allocation = lo_space->AllocateRaw(size);
545 } else if (space_index == kLargeFixedArray) {
546 new_allocation = lo_space->AllocateRawFixedArray(size);
547 } else {
548 ASSERT_EQ(kLargeCode, space_index);
549 new_allocation = lo_space->AllocateRawCode(size);
550 }
551 ASSERT(!new_allocation->IsFailure());
552 HeapObject* new_object = HeapObject::cast(new_allocation);
553 // Record all large objects in the same space.
554 address = new_object->address();
Andrei Popescu31002712010-02-23 13:46:05 +0000555 pages_[LO_SPACE].Add(address);
Steve Blockd0582a62009-12-15 09:54:21 +0000556 }
557 last_object_address_ = address;
558 return address;
559}
560
561
562// This returns the address of an object that has been described in the
563// snapshot as being offset bytes back in a particular space.
564HeapObject* Deserializer::GetAddressFromEnd(int space) {
565 int offset = source_->GetInt();
566 ASSERT(!SpaceIsLarge(space));
567 offset <<= kObjectAlignmentBits;
568 return HeapObject::FromAddress(high_water_[space] - offset);
569}
570
571
572// This returns the address of an object that has been described in the
573// snapshot as being offset bytes into a particular space.
574HeapObject* Deserializer::GetAddressFromStart(int space) {
575 int offset = source_->GetInt();
576 if (SpaceIsLarge(space)) {
577 // Large spaces have one object per 'page'.
578 return HeapObject::FromAddress(pages_[LO_SPACE][offset]);
579 }
580 offset <<= kObjectAlignmentBits;
581 if (space == NEW_SPACE) {
582 // New space has only one space - numbered 0.
583 return HeapObject::FromAddress(pages_[space][0] + offset);
584 }
585 ASSERT(SpaceIsPaged(space));
Leon Clarkee46be812010-01-19 14:06:41 +0000586 int page_of_pointee = offset >> kPageSizeBits;
Steve Blockd0582a62009-12-15 09:54:21 +0000587 Address object_address = pages_[space][page_of_pointee] +
588 (offset & Page::kPageAlignmentMask);
589 return HeapObject::FromAddress(object_address);
590}
591
592
593void Deserializer::Deserialize() {
594 // Don't GC while deserializing - just expand the heap.
595 AlwaysAllocateScope always_allocate;
596 // Don't use the free lists while deserializing.
597 LinearAllocationScope allocate_linearly;
598 // No active threads.
599 ASSERT_EQ(NULL, ThreadState::FirstInUse());
600 // No active handles.
601 ASSERT(HandleScopeImplementer::instance()->blocks()->is_empty());
Leon Clarked91b9f72010-01-27 17:25:45 +0000602 // Make sure the entire partial snapshot cache is traversed, filling it with
603 // valid object pointers.
604 partial_snapshot_cache_length_ = kPartialSnapshotCacheCapacity;
Steve Blockd0582a62009-12-15 09:54:21 +0000605 ASSERT_EQ(NULL, external_reference_decoder_);
606 external_reference_decoder_ = new ExternalReferenceDecoder();
Leon Clarked91b9f72010-01-27 17:25:45 +0000607 Heap::IterateStrongRoots(this, VISIT_ONLY_STRONG);
608 Heap::IterateWeakRoots(this, VISIT_ALL);
Leon Clarkee46be812010-01-19 14:06:41 +0000609}
610
611
612void Deserializer::DeserializePartial(Object** root) {
613 // Don't GC while deserializing - just expand the heap.
614 AlwaysAllocateScope always_allocate;
615 // Don't use the free lists while deserializing.
616 LinearAllocationScope allocate_linearly;
617 if (external_reference_decoder_ == NULL) {
618 external_reference_decoder_ = new ExternalReferenceDecoder();
619 }
620 VisitPointer(root);
621}
622
623
Leon Clarked91b9f72010-01-27 17:25:45 +0000624Deserializer::~Deserializer() {
625 ASSERT(source_->AtEOF());
Leon Clarkee46be812010-01-19 14:06:41 +0000626 if (external_reference_decoder_ != NULL) {
627 delete external_reference_decoder_;
628 external_reference_decoder_ = NULL;
629 }
Steve Blockd0582a62009-12-15 09:54:21 +0000630}
631
632
633// This is called on the roots. It is the driver of the deserialization
634// process. It is also called on the body of each function.
635void Deserializer::VisitPointers(Object** start, Object** end) {
636 // The space must be new space. Any other space would cause ReadChunk to try
637 // to update the remembered using NULL as the address.
638 ReadChunk(start, end, NEW_SPACE, NULL);
639}
640
641
642// This routine writes the new object into the pointer provided and then
643// returns true if the new object was in young space and false otherwise.
644// The reason for this strange interface is that otherwise the object is
645// written very late, which means the ByteArray map is not set up by the
646// time we need to use it to mark the space at the end of a page free (by
647// making it into a byte array).
648void Deserializer::ReadObject(int space_number,
649 Space* space,
650 Object** write_back) {
651 int size = source_->GetInt() << kObjectAlignmentBits;
652 Address address = Allocate(space_number, space, size);
653 *write_back = HeapObject::FromAddress(address);
654 Object** current = reinterpret_cast<Object**>(address);
655 Object** limit = current + (size >> kPointerSizeLog2);
Leon Clarkee46be812010-01-19 14:06:41 +0000656 if (FLAG_log_snapshot_positions) {
657 LOG(SnapshotPositionEvent(address, source_->position()));
658 }
Steve Blockd0582a62009-12-15 09:54:21 +0000659 ReadChunk(current, limit, space_number, address);
660}
661
662
Leon Clarkef7060e22010-06-03 12:02:55 +0100663// This macro is always used with a constant argument so it should all fold
664// away to almost nothing in the generated code. It might be nicer to do this
665// with the ternary operator but there are type issues with that.
666#define ASSIGN_DEST_SPACE(space_number) \
667 Space* dest_space; \
668 if (space_number == NEW_SPACE) { \
669 dest_space = Heap::new_space(); \
670 } else if (space_number == OLD_POINTER_SPACE) { \
671 dest_space = Heap::old_pointer_space(); \
672 } else if (space_number == OLD_DATA_SPACE) { \
673 dest_space = Heap::old_data_space(); \
674 } else if (space_number == CODE_SPACE) { \
675 dest_space = Heap::code_space(); \
676 } else if (space_number == MAP_SPACE) { \
677 dest_space = Heap::map_space(); \
678 } else if (space_number == CELL_SPACE) { \
679 dest_space = Heap::cell_space(); \
680 } else { \
681 ASSERT(space_number >= LO_SPACE); \
682 dest_space = Heap::lo_space(); \
683 }
684
685
686static const int kUnknownOffsetFromStart = -1;
Steve Blockd0582a62009-12-15 09:54:21 +0000687
688
689void Deserializer::ReadChunk(Object** current,
690 Object** limit,
Leon Clarkef7060e22010-06-03 12:02:55 +0100691 int source_space,
Steve Blockd0582a62009-12-15 09:54:21 +0000692 Address address) {
693 while (current < limit) {
694 int data = source_->Get();
695 switch (data) {
Leon Clarkef7060e22010-06-03 12:02:55 +0100696#define CASE_STATEMENT(where, how, within, space_number) \
697 case where + how + within + space_number: \
698 ASSERT((where & ~kPointedToMask) == 0); \
699 ASSERT((how & ~kHowToCodeMask) == 0); \
700 ASSERT((within & ~kWhereToPointMask) == 0); \
701 ASSERT((space_number & ~kSpaceMask) == 0);
702
703#define CASE_BODY(where, how, within, space_number_if_any, offset_from_start) \
704 { \
705 bool emit_write_barrier = false; \
706 bool current_was_incremented = false; \
707 int space_number = space_number_if_any == kAnyOldSpace ? \
708 (data & kSpaceMask) : space_number_if_any; \
709 if (where == kNewObject && how == kPlain && within == kStartOfObject) {\
710 ASSIGN_DEST_SPACE(space_number) \
711 ReadObject(space_number, dest_space, current); \
712 emit_write_barrier = \
713 (space_number == NEW_SPACE && source_space != NEW_SPACE); \
714 } else { \
715 Object* new_object = NULL; /* May not be a real Object pointer. */ \
716 if (where == kNewObject) { \
717 ASSIGN_DEST_SPACE(space_number) \
718 ReadObject(space_number, dest_space, &new_object); \
719 } else if (where == kRootArray) { \
720 int root_id = source_->GetInt(); \
721 new_object = Heap::roots_address()[root_id]; \
722 } else if (where == kPartialSnapshotCache) { \
723 int cache_index = source_->GetInt(); \
724 new_object = partial_snapshot_cache_[cache_index]; \
725 } else if (where == kExternalReference) { \
726 int reference_id = source_->GetInt(); \
727 Address address = \
728 external_reference_decoder_->Decode(reference_id); \
729 new_object = reinterpret_cast<Object*>(address); \
730 } else if (where == kBackref) { \
731 emit_write_barrier = \
732 (space_number == NEW_SPACE && source_space != NEW_SPACE); \
733 new_object = GetAddressFromEnd(data & kSpaceMask); \
734 } else { \
735 ASSERT(where == kFromStart); \
736 if (offset_from_start == kUnknownOffsetFromStart) { \
737 emit_write_barrier = \
738 (space_number == NEW_SPACE && source_space != NEW_SPACE); \
739 new_object = GetAddressFromStart(data & kSpaceMask); \
740 } else { \
741 Address object_address = pages_[space_number][0] + \
742 (offset_from_start << kObjectAlignmentBits); \
743 new_object = HeapObject::FromAddress(object_address); \
744 } \
745 } \
746 if (within == kFirstInstruction) { \
747 Code* new_code_object = reinterpret_cast<Code*>(new_object); \
748 new_object = reinterpret_cast<Object*>( \
749 new_code_object->instruction_start()); \
750 } \
751 if (how == kFromCode) { \
752 Address location_of_branch_data = \
753 reinterpret_cast<Address>(current); \
754 Assembler::set_target_at(location_of_branch_data, \
755 reinterpret_cast<Address>(new_object)); \
756 if (within == kFirstInstruction) { \
757 location_of_branch_data += Assembler::kCallTargetSize; \
758 current = reinterpret_cast<Object**>(location_of_branch_data); \
759 current_was_incremented = true; \
760 } \
761 } else { \
762 *current = new_object; \
763 } \
764 } \
765 if (emit_write_barrier) { \
766 Heap::RecordWrite(address, static_cast<int>( \
767 reinterpret_cast<Address>(current) - address)); \
768 } \
769 if (!current_was_incremented) { \
770 current++; /* Increment current if it wasn't done above. */ \
771 } \
772 break; \
773 } \
774
775// This generates a case and a body for each space. The large object spaces are
776// very rare in snapshots so they are grouped in one body.
777#define ONE_PER_SPACE(where, how, within) \
778 CASE_STATEMENT(where, how, within, NEW_SPACE) \
779 CASE_BODY(where, how, within, NEW_SPACE, kUnknownOffsetFromStart) \
780 CASE_STATEMENT(where, how, within, OLD_DATA_SPACE) \
781 CASE_BODY(where, how, within, OLD_DATA_SPACE, kUnknownOffsetFromStart) \
782 CASE_STATEMENT(where, how, within, OLD_POINTER_SPACE) \
783 CASE_BODY(where, how, within, OLD_POINTER_SPACE, kUnknownOffsetFromStart) \
784 CASE_STATEMENT(where, how, within, CODE_SPACE) \
785 CASE_BODY(where, how, within, CODE_SPACE, kUnknownOffsetFromStart) \
786 CASE_STATEMENT(where, how, within, CELL_SPACE) \
787 CASE_BODY(where, how, within, CELL_SPACE, kUnknownOffsetFromStart) \
788 CASE_STATEMENT(where, how, within, MAP_SPACE) \
789 CASE_BODY(where, how, within, MAP_SPACE, kUnknownOffsetFromStart) \
790 CASE_STATEMENT(where, how, within, kLargeData) \
791 CASE_STATEMENT(where, how, within, kLargeCode) \
792 CASE_STATEMENT(where, how, within, kLargeFixedArray) \
793 CASE_BODY(where, how, within, kAnyOldSpace, kUnknownOffsetFromStart)
794
795// This generates a case and a body for the new space (which has to do extra
796// write barrier handling) and handles the other spaces with 8 fall-through
797// cases and one body.
798#define ALL_SPACES(where, how, within) \
799 CASE_STATEMENT(where, how, within, NEW_SPACE) \
800 CASE_BODY(where, how, within, NEW_SPACE, kUnknownOffsetFromStart) \
801 CASE_STATEMENT(where, how, within, OLD_DATA_SPACE) \
802 CASE_STATEMENT(where, how, within, OLD_POINTER_SPACE) \
803 CASE_STATEMENT(where, how, within, CODE_SPACE) \
804 CASE_STATEMENT(where, how, within, CELL_SPACE) \
805 CASE_STATEMENT(where, how, within, MAP_SPACE) \
806 CASE_STATEMENT(where, how, within, kLargeData) \
807 CASE_STATEMENT(where, how, within, kLargeCode) \
808 CASE_STATEMENT(where, how, within, kLargeFixedArray) \
809 CASE_BODY(where, how, within, kAnyOldSpace, kUnknownOffsetFromStart)
810
811#define EMIT_COMMON_REFERENCE_PATTERNS(pseudo_space_number, \
812 space_number, \
813 offset_from_start) \
814 CASE_STATEMENT(kFromStart, kPlain, kStartOfObject, pseudo_space_number) \
815 CASE_BODY(kFromStart, kPlain, kStartOfObject, space_number, offset_from_start)
816
817 // We generate 15 cases and bodies that process special tags that combine
818 // the raw data tag and the length into one byte.
Steve Blockd0582a62009-12-15 09:54:21 +0000819#define RAW_CASE(index, size) \
Leon Clarkef7060e22010-06-03 12:02:55 +0100820 case kRawData + index: { \
Steve Blockd0582a62009-12-15 09:54:21 +0000821 byte* raw_data_out = reinterpret_cast<byte*>(current); \
822 source_->CopyRaw(raw_data_out, size); \
823 current = reinterpret_cast<Object**>(raw_data_out + size); \
824 break; \
825 }
826 COMMON_RAW_LENGTHS(RAW_CASE)
827#undef RAW_CASE
Leon Clarkef7060e22010-06-03 12:02:55 +0100828
829 // Deserialize a chunk of raw data that doesn't have one of the popular
830 // lengths.
831 case kRawData: {
Steve Blockd0582a62009-12-15 09:54:21 +0000832 int size = source_->GetInt();
833 byte* raw_data_out = reinterpret_cast<byte*>(current);
834 source_->CopyRaw(raw_data_out, size);
835 current = reinterpret_cast<Object**>(raw_data_out + size);
836 break;
837 }
Leon Clarkef7060e22010-06-03 12:02:55 +0100838
839 // Deserialize a new object and write a pointer to it to the current
840 // object.
841 ONE_PER_SPACE(kNewObject, kPlain, kStartOfObject)
842 // Deserialize a new code object and write a pointer to its first
843 // instruction to the current code object.
844 ONE_PER_SPACE(kNewObject, kFromCode, kFirstInstruction)
845 // Find a recently deserialized object using its offset from the current
846 // allocation point and write a pointer to it to the current object.
847 ALL_SPACES(kBackref, kPlain, kStartOfObject)
848 // Find a recently deserialized code object using its offset from the
849 // current allocation point and write a pointer to its first instruction
850 // to the current code object.
851 ALL_SPACES(kBackref, kFromCode, kFirstInstruction)
852 // Find an already deserialized object using its offset from the start
853 // and write a pointer to it to the current object.
854 ALL_SPACES(kFromStart, kPlain, kStartOfObject)
855 // Find an already deserialized code object using its offset from the
856 // start and write a pointer to its first instruction to the current code
857 // object.
858 ALL_SPACES(kFromStart, kFromCode, kFirstInstruction)
859 // Find an already deserialized object at one of the predetermined popular
860 // offsets from the start and write a pointer to it in the current object.
861 COMMON_REFERENCE_PATTERNS(EMIT_COMMON_REFERENCE_PATTERNS)
862 // Find an object in the roots array and write a pointer to it to the
863 // current object.
864 CASE_STATEMENT(kRootArray, kPlain, kStartOfObject, 0)
865 CASE_BODY(kRootArray, kPlain, kStartOfObject, 0, kUnknownOffsetFromStart)
866 // Find an object in the partial snapshots cache and write a pointer to it
867 // to the current object.
868 CASE_STATEMENT(kPartialSnapshotCache, kPlain, kStartOfObject, 0)
869 CASE_BODY(kPartialSnapshotCache,
870 kPlain,
871 kStartOfObject,
872 0,
873 kUnknownOffsetFromStart)
874 // Find an external reference and write a pointer to it to the current
875 // object.
876 CASE_STATEMENT(kExternalReference, kPlain, kStartOfObject, 0)
877 CASE_BODY(kExternalReference,
878 kPlain,
879 kStartOfObject,
880 0,
881 kUnknownOffsetFromStart)
882 // Find an external reference and write a pointer to it in the current
883 // code object.
884 CASE_STATEMENT(kExternalReference, kFromCode, kStartOfObject, 0)
885 CASE_BODY(kExternalReference,
886 kFromCode,
887 kStartOfObject,
888 0,
889 kUnknownOffsetFromStart)
890
891#undef CASE_STATEMENT
892#undef CASE_BODY
893#undef ONE_PER_SPACE
894#undef ALL_SPACES
895#undef EMIT_COMMON_REFERENCE_PATTERNS
896#undef ASSIGN_DEST_SPACE
897
898 case kNewPage: {
Steve Blockd0582a62009-12-15 09:54:21 +0000899 int space = source_->Get();
900 pages_[space].Add(last_object_address_);
Steve Block6ded16b2010-05-10 14:33:55 +0100901 if (space == CODE_SPACE) {
902 CPU::FlushICache(last_object_address_, Page::kPageSize);
903 }
Steve Blockd0582a62009-12-15 09:54:21 +0000904 break;
905 }
Leon Clarkef7060e22010-06-03 12:02:55 +0100906
907 case kNativesStringResource: {
Steve Blockd0582a62009-12-15 09:54:21 +0000908 int index = source_->Get();
909 Vector<const char> source_vector = Natives::GetScriptSource(index);
910 NativesExternalStringResource* resource =
911 new NativesExternalStringResource(source_vector.start());
912 *current++ = reinterpret_cast<Object*>(resource);
913 break;
914 }
Leon Clarkef7060e22010-06-03 12:02:55 +0100915
916 case kSynchronize: {
Leon Clarked91b9f72010-01-27 17:25:45 +0000917 // If we get here then that indicates that you have a mismatch between
918 // the number of GC roots when serializing and deserializing.
919 UNREACHABLE();
920 }
Leon Clarkef7060e22010-06-03 12:02:55 +0100921
Steve Blockd0582a62009-12-15 09:54:21 +0000922 default:
923 UNREACHABLE();
924 }
925 }
926 ASSERT_EQ(current, limit);
927}
928
929
930void SnapshotByteSink::PutInt(uintptr_t integer, const char* description) {
931 const int max_shift = ((kPointerSize * kBitsPerByte) / 7) * 7;
932 for (int shift = max_shift; shift > 0; shift -= 7) {
933 if (integer >= static_cast<uintptr_t>(1u) << shift) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000934 Put((static_cast<int>((integer >> shift)) & 0x7f) | 0x80, "IntPart");
Steve Blockd0582a62009-12-15 09:54:21 +0000935 }
936 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000937 PutSection(static_cast<int>(integer & 0x7f), "IntLastPart");
Steve Blockd0582a62009-12-15 09:54:21 +0000938}
939
Steve Blocka7e24c12009-10-30 11:49:00 +0000940#ifdef DEBUG
Steve Blockd0582a62009-12-15 09:54:21 +0000941
942void Deserializer::Synchronize(const char* tag) {
943 int data = source_->Get();
944 // If this assert fails then that indicates that you have a mismatch between
945 // the number of GC roots when serializing and deserializing.
Leon Clarkef7060e22010-06-03 12:02:55 +0100946 ASSERT_EQ(kSynchronize, data);
Steve Blockd0582a62009-12-15 09:54:21 +0000947 do {
948 int character = source_->Get();
949 if (character == 0) break;
950 if (FLAG_debug_serialization) {
951 PrintF("%c", character);
952 }
953 } while (true);
954 if (FLAG_debug_serialization) {
955 PrintF("\n");
956 }
957}
958
Steve Blocka7e24c12009-10-30 11:49:00 +0000959
960void Serializer::Synchronize(const char* tag) {
Leon Clarkef7060e22010-06-03 12:02:55 +0100961 sink_->Put(kSynchronize, tag);
Steve Blockd0582a62009-12-15 09:54:21 +0000962 int character;
963 do {
964 character = *tag++;
965 sink_->PutSection(character, "TagCharacter");
966 } while (character != 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000967}
Steve Blockd0582a62009-12-15 09:54:21 +0000968
Steve Blocka7e24c12009-10-30 11:49:00 +0000969#endif
970
Steve Blockd0582a62009-12-15 09:54:21 +0000971Serializer::Serializer(SnapshotByteSink* sink)
972 : sink_(sink),
973 current_root_index_(0),
Andrei Popescu31002712010-02-23 13:46:05 +0000974 external_reference_encoder_(new ExternalReferenceEncoder),
Leon Clarkee46be812010-01-19 14:06:41 +0000975 large_object_total_(0) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000976 for (int i = 0; i <= LAST_SPACE; i++) {
Steve Blockd0582a62009-12-15 09:54:21 +0000977 fullness_[i] = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000978 }
979}
980
981
Andrei Popescu31002712010-02-23 13:46:05 +0000982Serializer::~Serializer() {
983 delete external_reference_encoder_;
984}
985
986
Leon Clarked91b9f72010-01-27 17:25:45 +0000987void StartupSerializer::SerializeStrongReferences() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000988 // No active threads.
989 CHECK_EQ(NULL, ThreadState::FirstInUse());
990 // No active or weak handles.
991 CHECK(HandleScopeImplementer::instance()->blocks()->is_empty());
992 CHECK_EQ(0, GlobalHandles::NumberOfWeakHandles());
Steve Blockd0582a62009-12-15 09:54:21 +0000993 // We don't support serializing installed extensions.
994 for (RegisteredExtension* ext = RegisteredExtension::first_extension();
995 ext != NULL;
996 ext = ext->next()) {
997 CHECK_NE(v8::INSTALLED, ext->state());
998 }
Leon Clarked91b9f72010-01-27 17:25:45 +0000999 Heap::IterateStrongRoots(this, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +00001000}
1001
1002
Leon Clarked91b9f72010-01-27 17:25:45 +00001003void PartialSerializer::Serialize(Object** object) {
Leon Clarkee46be812010-01-19 14:06:41 +00001004 this->VisitPointer(object);
Leon Clarked91b9f72010-01-27 17:25:45 +00001005
1006 // After we have done the partial serialization the partial snapshot cache
1007 // will contain some references needed to decode the partial snapshot. We
1008 // fill it up with undefineds so it has a predictable length so the
1009 // deserialization code doesn't need to know the length.
1010 for (int index = partial_snapshot_cache_length_;
1011 index < kPartialSnapshotCacheCapacity;
1012 index++) {
1013 partial_snapshot_cache_[index] = Heap::undefined_value();
1014 startup_serializer_->VisitPointer(&partial_snapshot_cache_[index]);
1015 }
1016 partial_snapshot_cache_length_ = kPartialSnapshotCacheCapacity;
Leon Clarkee46be812010-01-19 14:06:41 +00001017}
1018
1019
Steve Blocka7e24c12009-10-30 11:49:00 +00001020void Serializer::VisitPointers(Object** start, Object** end) {
Steve Blockd0582a62009-12-15 09:54:21 +00001021 for (Object** current = start; current < end; current++) {
1022 if ((*current)->IsSmi()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001023 sink_->Put(kRawData, "RawData");
Steve Blockd0582a62009-12-15 09:54:21 +00001024 sink_->PutInt(kPointerSize, "length");
1025 for (int i = 0; i < kPointerSize; i++) {
1026 sink_->Put(reinterpret_cast<byte*>(current)[i], "Byte");
1027 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001028 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01001029 SerializeObject(*current, kPlain, kStartOfObject);
Steve Blocka7e24c12009-10-30 11:49:00 +00001030 }
1031 }
1032}
1033
1034
Leon Clarked91b9f72010-01-27 17:25:45 +00001035Object* SerializerDeserializer::partial_snapshot_cache_[
1036 kPartialSnapshotCacheCapacity];
1037int SerializerDeserializer::partial_snapshot_cache_length_ = 0;
1038
1039
1040// This ensures that the partial snapshot cache keeps things alive during GC and
1041// tracks their movement. When it is called during serialization of the startup
1042// snapshot the partial snapshot is empty, so nothing happens. When the partial
1043// (context) snapshot is created, this array is populated with the pointers that
1044// the partial snapshot will need. As that happens we emit serialized objects to
1045// the startup snapshot that correspond to the elements of this cache array. On
1046// deserialization we therefore need to visit the cache array. This fills it up
1047// with pointers to deserialized objects.
Steve Block6ded16b2010-05-10 14:33:55 +01001048void SerializerDeserializer::Iterate(ObjectVisitor* visitor) {
Leon Clarked91b9f72010-01-27 17:25:45 +00001049 visitor->VisitPointers(
1050 &partial_snapshot_cache_[0],
1051 &partial_snapshot_cache_[partial_snapshot_cache_length_]);
1052}
1053
1054
1055// When deserializing we need to set the size of the snapshot cache. This means
1056// the root iteration code (above) will iterate over array elements, writing the
1057// references to deserialized objects in them.
1058void SerializerDeserializer::SetSnapshotCacheSize(int size) {
1059 partial_snapshot_cache_length_ = size;
1060}
1061
1062
1063int PartialSerializer::PartialSnapshotCacheIndex(HeapObject* heap_object) {
1064 for (int i = 0; i < partial_snapshot_cache_length_; i++) {
1065 Object* entry = partial_snapshot_cache_[i];
1066 if (entry == heap_object) return i;
1067 }
Andrei Popescu31002712010-02-23 13:46:05 +00001068
Leon Clarked91b9f72010-01-27 17:25:45 +00001069 // We didn't find the object in the cache. So we add it to the cache and
1070 // then visit the pointer so that it becomes part of the startup snapshot
1071 // and we can refer to it from the partial snapshot.
1072 int length = partial_snapshot_cache_length_;
1073 CHECK(length < kPartialSnapshotCacheCapacity);
1074 partial_snapshot_cache_[length] = heap_object;
1075 startup_serializer_->VisitPointer(&partial_snapshot_cache_[length]);
1076 // We don't recurse from the startup snapshot generator into the partial
1077 // snapshot generator.
1078 ASSERT(length == partial_snapshot_cache_length_);
1079 return partial_snapshot_cache_length_++;
1080}
1081
1082
1083int PartialSerializer::RootIndex(HeapObject* heap_object) {
Leon Clarkee46be812010-01-19 14:06:41 +00001084 for (int i = 0; i < Heap::kRootListLength; i++) {
1085 Object* root = Heap::roots_address()[i];
1086 if (root == heap_object) return i;
1087 }
1088 return kInvalidRootIndex;
1089}
1090
1091
Leon Clarked91b9f72010-01-27 17:25:45 +00001092// Encode the location of an already deserialized object in order to write its
1093// location into a later object. We can encode the location as an offset from
1094// the start of the deserialized objects or as an offset backwards from the
1095// current allocation pointer.
1096void Serializer::SerializeReferenceToPreviousObject(
1097 int space,
1098 int address,
Leon Clarkef7060e22010-06-03 12:02:55 +01001099 HowToCode how_to_code,
1100 WhereToPoint where_to_point) {
Leon Clarked91b9f72010-01-27 17:25:45 +00001101 int offset = CurrentAllocationAddress(space) - address;
1102 bool from_start = true;
1103 if (SpaceIsPaged(space)) {
1104 // For paged space it is simple to encode back from current allocation if
1105 // the object is on the same page as the current allocation pointer.
1106 if ((CurrentAllocationAddress(space) >> kPageSizeBits) ==
1107 (address >> kPageSizeBits)) {
1108 from_start = false;
1109 address = offset;
1110 }
1111 } else if (space == NEW_SPACE) {
1112 // For new space it is always simple to encode back from current allocation.
1113 if (offset < address) {
1114 from_start = false;
1115 address = offset;
1116 }
1117 }
1118 // If we are actually dealing with real offsets (and not a numbering of
1119 // all objects) then we should shift out the bits that are always 0.
1120 if (!SpaceIsLarge(space)) address >>= kObjectAlignmentBits;
Leon Clarkef7060e22010-06-03 12:02:55 +01001121 if (from_start) {
1122#define COMMON_REFS_CASE(pseudo_space, actual_space, offset) \
1123 if (space == actual_space && address == offset && \
1124 how_to_code == kPlain && where_to_point == kStartOfObject) { \
1125 sink_->Put(kFromStart + how_to_code + where_to_point + \
1126 pseudo_space, "RefSer"); \
1127 } else /* NOLINT */
1128 COMMON_REFERENCE_PATTERNS(COMMON_REFS_CASE)
1129#undef COMMON_REFS_CASE
1130 { /* NOLINT */
1131 sink_->Put(kFromStart + how_to_code + where_to_point + space, "RefSer");
Leon Clarked91b9f72010-01-27 17:25:45 +00001132 sink_->PutInt(address, "address");
1133 }
1134 } else {
Leon Clarkef7060e22010-06-03 12:02:55 +01001135 sink_->Put(kBackref + how_to_code + where_to_point + space, "BackRefSer");
1136 sink_->PutInt(address, "address");
Leon Clarked91b9f72010-01-27 17:25:45 +00001137 }
1138}
1139
1140
1141void StartupSerializer::SerializeObject(
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001142 Object* o,
Leon Clarkef7060e22010-06-03 12:02:55 +01001143 HowToCode how_to_code,
1144 WhereToPoint where_to_point) {
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001145 CHECK(o->IsHeapObject());
1146 HeapObject* heap_object = HeapObject::cast(o);
Leon Clarked91b9f72010-01-27 17:25:45 +00001147
1148 if (address_mapper_.IsMapped(heap_object)) {
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001149 int space = SpaceOfAlreadySerializedObject(heap_object);
Leon Clarked91b9f72010-01-27 17:25:45 +00001150 int address = address_mapper_.MappedTo(heap_object);
1151 SerializeReferenceToPreviousObject(space,
1152 address,
Leon Clarkef7060e22010-06-03 12:02:55 +01001153 how_to_code,
1154 where_to_point);
Leon Clarked91b9f72010-01-27 17:25:45 +00001155 } else {
1156 // Object has not yet been serialized. Serialize it here.
1157 ObjectSerializer object_serializer(this,
1158 heap_object,
1159 sink_,
Leon Clarkef7060e22010-06-03 12:02:55 +01001160 how_to_code,
1161 where_to_point);
Leon Clarked91b9f72010-01-27 17:25:45 +00001162 object_serializer.Serialize();
1163 }
1164}
1165
1166
1167void StartupSerializer::SerializeWeakReferences() {
1168 for (int i = partial_snapshot_cache_length_;
1169 i < kPartialSnapshotCacheCapacity;
1170 i++) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001171 sink_->Put(kRootArray + kPlain + kStartOfObject, "RootSerialization");
Leon Clarked91b9f72010-01-27 17:25:45 +00001172 sink_->PutInt(Heap::kUndefinedValueRootIndex, "root_index");
1173 }
1174 Heap::IterateWeakRoots(this, VISIT_ALL);
1175}
1176
1177
1178void PartialSerializer::SerializeObject(
1179 Object* o,
Leon Clarkef7060e22010-06-03 12:02:55 +01001180 HowToCode how_to_code,
1181 WhereToPoint where_to_point) {
Leon Clarked91b9f72010-01-27 17:25:45 +00001182 CHECK(o->IsHeapObject());
1183 HeapObject* heap_object = HeapObject::cast(o);
1184
1185 int root_index;
1186 if ((root_index = RootIndex(heap_object)) != kInvalidRootIndex) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001187 sink_->Put(kRootArray + how_to_code + where_to_point, "RootSerialization");
Leon Clarked91b9f72010-01-27 17:25:45 +00001188 sink_->PutInt(root_index, "root_index");
1189 return;
1190 }
1191
1192 if (ShouldBeInThePartialSnapshotCache(heap_object)) {
1193 int cache_index = PartialSnapshotCacheIndex(heap_object);
Leon Clarkef7060e22010-06-03 12:02:55 +01001194 sink_->Put(kPartialSnapshotCache + how_to_code + where_to_point,
1195 "PartialSnapshotCache");
Leon Clarked91b9f72010-01-27 17:25:45 +00001196 sink_->PutInt(cache_index, "partial_snapshot_cache_index");
1197 return;
1198 }
1199
1200 // Pointers from the partial snapshot to the objects in the startup snapshot
1201 // should go through the root array or through the partial snapshot cache.
1202 // If this is not the case you may have to add something to the root array.
1203 ASSERT(!startup_serializer_->address_mapper()->IsMapped(heap_object));
1204 // All the symbols that the partial snapshot needs should be either in the
1205 // root table or in the partial snapshot cache.
1206 ASSERT(!heap_object->IsSymbol());
1207
1208 if (address_mapper_.IsMapped(heap_object)) {
1209 int space = SpaceOfAlreadySerializedObject(heap_object);
1210 int address = address_mapper_.MappedTo(heap_object);
1211 SerializeReferenceToPreviousObject(space,
1212 address,
Leon Clarkef7060e22010-06-03 12:02:55 +01001213 how_to_code,
1214 where_to_point);
Steve Blockd0582a62009-12-15 09:54:21 +00001215 } else {
1216 // Object has not yet been serialized. Serialize it here.
1217 ObjectSerializer serializer(this,
1218 heap_object,
1219 sink_,
Leon Clarkef7060e22010-06-03 12:02:55 +01001220 how_to_code,
1221 where_to_point);
Steve Blockd0582a62009-12-15 09:54:21 +00001222 serializer.Serialize();
1223 }
1224}
1225
1226
Steve Blockd0582a62009-12-15 09:54:21 +00001227void Serializer::ObjectSerializer::Serialize() {
1228 int space = Serializer::SpaceOfObject(object_);
1229 int size = object_->Size();
1230
Leon Clarkef7060e22010-06-03 12:02:55 +01001231 sink_->Put(kNewObject + reference_representation_ + space,
1232 "ObjectSerialization");
Steve Blockd0582a62009-12-15 09:54:21 +00001233 sink_->PutInt(size >> kObjectAlignmentBits, "Size in words");
1234
Leon Clarkee46be812010-01-19 14:06:41 +00001235 LOG(SnapshotPositionEvent(object_->address(), sink_->Position()));
1236
Steve Blockd0582a62009-12-15 09:54:21 +00001237 // Mark this object as already serialized.
1238 bool start_new_page;
Leon Clarked91b9f72010-01-27 17:25:45 +00001239 int offset = serializer_->Allocate(space, size, &start_new_page);
1240 serializer_->address_mapper()->AddMapping(object_, offset);
Steve Blockd0582a62009-12-15 09:54:21 +00001241 if (start_new_page) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001242 sink_->Put(kNewPage, "NewPage");
Steve Blockd0582a62009-12-15 09:54:21 +00001243 sink_->PutSection(space, "NewPageSpace");
1244 }
1245
1246 // Serialize the map (first word of the object).
Leon Clarkef7060e22010-06-03 12:02:55 +01001247 serializer_->SerializeObject(object_->map(), kPlain, kStartOfObject);
Steve Blockd0582a62009-12-15 09:54:21 +00001248
1249 // Serialize the rest of the object.
1250 CHECK_EQ(0, bytes_processed_so_far_);
1251 bytes_processed_so_far_ = kPointerSize;
1252 object_->IterateBody(object_->map()->instance_type(), size, this);
1253 OutputRawData(object_->address() + size);
1254}
1255
1256
1257void Serializer::ObjectSerializer::VisitPointers(Object** start,
1258 Object** end) {
1259 Object** current = start;
1260 while (current < end) {
1261 while (current < end && (*current)->IsSmi()) current++;
1262 if (current < end) OutputRawData(reinterpret_cast<Address>(current));
1263
1264 while (current < end && !(*current)->IsSmi()) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001265 serializer_->SerializeObject(*current, kPlain, kStartOfObject);
Steve Blockd0582a62009-12-15 09:54:21 +00001266 bytes_processed_so_far_ += kPointerSize;
1267 current++;
1268 }
1269 }
1270}
1271
1272
1273void Serializer::ObjectSerializer::VisitExternalReferences(Address* start,
1274 Address* end) {
1275 Address references_start = reinterpret_cast<Address>(start);
1276 OutputRawData(references_start);
1277
1278 for (Address* current = start; current < end; current++) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001279 sink_->Put(kExternalReference + kPlain + kStartOfObject, "ExternalRef");
Steve Blockd0582a62009-12-15 09:54:21 +00001280 int reference_id = serializer_->EncodeExternalReference(*current);
1281 sink_->PutInt(reference_id, "reference id");
1282 }
1283 bytes_processed_so_far_ += static_cast<int>((end - start) * kPointerSize);
1284}
1285
1286
1287void Serializer::ObjectSerializer::VisitRuntimeEntry(RelocInfo* rinfo) {
1288 Address target_start = rinfo->target_address_address();
1289 OutputRawData(target_start);
1290 Address target = rinfo->target_address();
1291 uint32_t encoding = serializer_->EncodeExternalReference(target);
1292 CHECK(target == NULL ? encoding == 0 : encoding != 0);
Leon Clarkef7060e22010-06-03 12:02:55 +01001293 int representation;
1294 // Can't use a ternary operator because of gcc.
1295 if (rinfo->IsCodedSpecially()) {
1296 representation = kStartOfObject + kFromCode;
1297 } else {
1298 representation = kStartOfObject + kPlain;
1299 }
1300 sink_->Put(kExternalReference + representation, "ExternalReference");
Steve Blockd0582a62009-12-15 09:54:21 +00001301 sink_->PutInt(encoding, "reference id");
Leon Clarkef7060e22010-06-03 12:02:55 +01001302 bytes_processed_so_far_ += rinfo->target_address_size();
Steve Blockd0582a62009-12-15 09:54:21 +00001303}
1304
1305
1306void Serializer::ObjectSerializer::VisitCodeTarget(RelocInfo* rinfo) {
1307 CHECK(RelocInfo::IsCodeTarget(rinfo->rmode()));
1308 Address target_start = rinfo->target_address_address();
1309 OutputRawData(target_start);
1310 Code* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
Leon Clarkef7060e22010-06-03 12:02:55 +01001311 serializer_->SerializeObject(target, kFromCode, kFirstInstruction);
1312 bytes_processed_so_far_ += rinfo->target_address_size();
Steve Blockd0582a62009-12-15 09:54:21 +00001313}
1314
1315
1316void Serializer::ObjectSerializer::VisitExternalAsciiString(
1317 v8::String::ExternalAsciiStringResource** resource_pointer) {
1318 Address references_start = reinterpret_cast<Address>(resource_pointer);
1319 OutputRawData(references_start);
1320 for (int i = 0; i < Natives::GetBuiltinsCount(); i++) {
1321 Object* source = Heap::natives_source_cache()->get(i);
1322 if (!source->IsUndefined()) {
1323 ExternalAsciiString* string = ExternalAsciiString::cast(source);
1324 typedef v8::String::ExternalAsciiStringResource Resource;
1325 Resource* resource = string->resource();
1326 if (resource == *resource_pointer) {
Leon Clarkef7060e22010-06-03 12:02:55 +01001327 sink_->Put(kNativesStringResource, "NativesStringResource");
Steve Blockd0582a62009-12-15 09:54:21 +00001328 sink_->PutSection(i, "NativesStringResourceEnd");
1329 bytes_processed_so_far_ += sizeof(resource);
1330 return;
1331 }
1332 }
1333 }
1334 // One of the strings in the natives cache should match the resource. We
1335 // can't serialize any other kinds of external strings.
1336 UNREACHABLE();
1337}
1338
1339
1340void Serializer::ObjectSerializer::OutputRawData(Address up_to) {
1341 Address object_start = object_->address();
1342 int up_to_offset = static_cast<int>(up_to - object_start);
1343 int skipped = up_to_offset - bytes_processed_so_far_;
1344 // This assert will fail if the reloc info gives us the target_address_address
1345 // locations in a non-ascending order. Luckily that doesn't happen.
1346 ASSERT(skipped >= 0);
1347 if (skipped != 0) {
1348 Address base = object_start + bytes_processed_so_far_;
1349#define RAW_CASE(index, length) \
1350 if (skipped == length) { \
Leon Clarkef7060e22010-06-03 12:02:55 +01001351 sink_->PutSection(kRawData + index, "RawDataFixed"); \
Steve Blockd0582a62009-12-15 09:54:21 +00001352 } else /* NOLINT */
1353 COMMON_RAW_LENGTHS(RAW_CASE)
1354#undef RAW_CASE
1355 { /* NOLINT */
Leon Clarkef7060e22010-06-03 12:02:55 +01001356 sink_->Put(kRawData, "RawData");
Steve Blockd0582a62009-12-15 09:54:21 +00001357 sink_->PutInt(skipped, "length");
1358 }
1359 for (int i = 0; i < skipped; i++) {
1360 unsigned int data = base[i];
1361 sink_->PutSection(data, "Byte");
1362 }
1363 bytes_processed_so_far_ += skipped;
1364 }
1365}
1366
1367
1368int Serializer::SpaceOfObject(HeapObject* object) {
1369 for (int i = FIRST_SPACE; i <= LAST_SPACE; i++) {
1370 AllocationSpace s = static_cast<AllocationSpace>(i);
1371 if (Heap::InSpace(object, s)) {
1372 if (i == LO_SPACE) {
1373 if (object->IsCode()) {
1374 return kLargeCode;
1375 } else if (object->IsFixedArray()) {
1376 return kLargeFixedArray;
1377 } else {
1378 return kLargeData;
1379 }
1380 }
1381 return i;
1382 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001383 }
1384 UNREACHABLE();
Steve Blockd0582a62009-12-15 09:54:21 +00001385 return 0;
1386}
1387
1388
1389int Serializer::SpaceOfAlreadySerializedObject(HeapObject* object) {
1390 for (int i = FIRST_SPACE; i <= LAST_SPACE; i++) {
1391 AllocationSpace s = static_cast<AllocationSpace>(i);
1392 if (Heap::InSpace(object, s)) {
1393 return i;
1394 }
1395 }
1396 UNREACHABLE();
1397 return 0;
1398}
1399
1400
1401int Serializer::Allocate(int space, int size, bool* new_page) {
1402 CHECK(space >= 0 && space < kNumberOfSpaces);
1403 if (SpaceIsLarge(space)) {
1404 // In large object space we merely number the objects instead of trying to
1405 // determine some sort of address.
1406 *new_page = true;
Leon Clarkee46be812010-01-19 14:06:41 +00001407 large_object_total_ += size;
Steve Blockd0582a62009-12-15 09:54:21 +00001408 return fullness_[LO_SPACE]++;
1409 }
1410 *new_page = false;
1411 if (fullness_[space] == 0) {
1412 *new_page = true;
1413 }
1414 if (SpaceIsPaged(space)) {
1415 // Paged spaces are a little special. We encode their addresses as if the
1416 // pages were all contiguous and each page were filled up in the range
1417 // 0 - Page::kObjectAreaSize. In practice the pages may not be contiguous
1418 // and allocation does not start at offset 0 in the page, but this scheme
1419 // means the deserializer can get the page number quickly by shifting the
1420 // serialized address.
1421 CHECK(IsPowerOf2(Page::kPageSize));
1422 int used_in_this_page = (fullness_[space] & (Page::kPageSize - 1));
1423 CHECK(size <= Page::kObjectAreaSize);
1424 if (used_in_this_page + size > Page::kObjectAreaSize) {
1425 *new_page = true;
1426 fullness_[space] = RoundUp(fullness_[space], Page::kPageSize);
1427 }
1428 }
1429 int allocation_address = fullness_[space];
1430 fullness_[space] = allocation_address + size;
1431 return allocation_address;
Steve Blocka7e24c12009-10-30 11:49:00 +00001432}
1433
1434
1435} } // namespace v8::internal