blob: dcaa1011555b203d632066c9235fce7068e605d2 [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
663#define ONE_CASE_PER_SPACE(base_tag) \
664 case (base_tag) + NEW_SPACE: /* NOLINT */ \
665 case (base_tag) + OLD_POINTER_SPACE: /* NOLINT */ \
666 case (base_tag) + OLD_DATA_SPACE: /* NOLINT */ \
667 case (base_tag) + CODE_SPACE: /* NOLINT */ \
668 case (base_tag) + MAP_SPACE: /* NOLINT */ \
669 case (base_tag) + CELL_SPACE: /* NOLINT */ \
670 case (base_tag) + kLargeData: /* NOLINT */ \
671 case (base_tag) + kLargeCode: /* NOLINT */ \
672 case (base_tag) + kLargeFixedArray: /* NOLINT */
673
674
675void Deserializer::ReadChunk(Object** current,
676 Object** limit,
677 int space,
678 Address address) {
679 while (current < limit) {
680 int data = source_->Get();
681 switch (data) {
682#define RAW_CASE(index, size) \
683 case RAW_DATA_SERIALIZATION + index: { \
684 byte* raw_data_out = reinterpret_cast<byte*>(current); \
685 source_->CopyRaw(raw_data_out, size); \
686 current = reinterpret_cast<Object**>(raw_data_out + size); \
687 break; \
688 }
689 COMMON_RAW_LENGTHS(RAW_CASE)
690#undef RAW_CASE
691 case RAW_DATA_SERIALIZATION: {
692 int size = source_->GetInt();
693 byte* raw_data_out = reinterpret_cast<byte*>(current);
694 source_->CopyRaw(raw_data_out, size);
695 current = reinterpret_cast<Object**>(raw_data_out + size);
696 break;
697 }
698 case OBJECT_SERIALIZATION + NEW_SPACE: {
699 ReadObject(NEW_SPACE, Heap::new_space(), current);
700 if (space != NEW_SPACE) {
701 Heap::RecordWrite(address, static_cast<int>(
702 reinterpret_cast<Address>(current) - address));
703 }
704 current++;
705 break;
706 }
707 case OBJECT_SERIALIZATION + OLD_DATA_SPACE:
708 ReadObject(OLD_DATA_SPACE, Heap::old_data_space(), current++);
709 break;
710 case OBJECT_SERIALIZATION + OLD_POINTER_SPACE:
711 ReadObject(OLD_POINTER_SPACE, Heap::old_pointer_space(), current++);
712 break;
713 case OBJECT_SERIALIZATION + MAP_SPACE:
714 ReadObject(MAP_SPACE, Heap::map_space(), current++);
715 break;
716 case OBJECT_SERIALIZATION + CODE_SPACE:
717 ReadObject(CODE_SPACE, Heap::code_space(), current++);
Steve Blockd0582a62009-12-15 09:54:21 +0000718 break;
719 case OBJECT_SERIALIZATION + CELL_SPACE:
720 ReadObject(CELL_SPACE, Heap::cell_space(), current++);
721 break;
722 case OBJECT_SERIALIZATION + kLargeData:
723 ReadObject(kLargeData, Heap::lo_space(), current++);
724 break;
725 case OBJECT_SERIALIZATION + kLargeCode:
726 ReadObject(kLargeCode, Heap::lo_space(), current++);
Steve Blockd0582a62009-12-15 09:54:21 +0000727 break;
728 case OBJECT_SERIALIZATION + kLargeFixedArray:
729 ReadObject(kLargeFixedArray, Heap::lo_space(), current++);
730 break;
731 case CODE_OBJECT_SERIALIZATION + kLargeCode: {
732 Object* new_code_object = NULL;
733 ReadObject(kLargeCode, Heap::lo_space(), &new_code_object);
734 Code* code_object = reinterpret_cast<Code*>(new_code_object);
Steve Blockd0582a62009-12-15 09:54:21 +0000735 // Setting a branch/call to another code object from code.
736 Address location_of_branch_data = reinterpret_cast<Address>(current);
737 Assembler::set_target_at(location_of_branch_data,
738 code_object->instruction_start());
739 location_of_branch_data += Assembler::kCallTargetSize;
740 current = reinterpret_cast<Object**>(location_of_branch_data);
741 break;
742 }
743 case CODE_OBJECT_SERIALIZATION + CODE_SPACE: {
744 Object* new_code_object = NULL;
745 ReadObject(CODE_SPACE, Heap::code_space(), &new_code_object);
746 Code* code_object = reinterpret_cast<Code*>(new_code_object);
Steve Blockd0582a62009-12-15 09:54:21 +0000747 // Setting a branch/call to another code object from code.
748 Address location_of_branch_data = reinterpret_cast<Address>(current);
749 Assembler::set_target_at(location_of_branch_data,
750 code_object->instruction_start());
751 location_of_branch_data += Assembler::kCallTargetSize;
752 current = reinterpret_cast<Object**>(location_of_branch_data);
753 break;
754 }
755 ONE_CASE_PER_SPACE(BACKREF_SERIALIZATION) {
756 // Write a backreference to an object we unpacked earlier.
757 int backref_space = (data & kSpaceMask);
758 if (backref_space == NEW_SPACE && space != NEW_SPACE) {
759 Heap::RecordWrite(address, static_cast<int>(
760 reinterpret_cast<Address>(current) - address));
761 }
762 *current++ = GetAddressFromEnd(backref_space);
763 break;
764 }
765 ONE_CASE_PER_SPACE(REFERENCE_SERIALIZATION) {
766 // Write a reference to an object we unpacked earlier.
767 int reference_space = (data & kSpaceMask);
768 if (reference_space == NEW_SPACE && space != NEW_SPACE) {
769 Heap::RecordWrite(address, static_cast<int>(
770 reinterpret_cast<Address>(current) - address));
771 }
772 *current++ = GetAddressFromStart(reference_space);
773 break;
774 }
775#define COMMON_REFS_CASE(index, reference_space, address) \
776 case REFERENCE_SERIALIZATION + index: { \
777 ASSERT(SpaceIsPaged(reference_space)); \
778 Address object_address = \
779 pages_[reference_space][0] + (address << kObjectAlignmentBits); \
780 *current++ = HeapObject::FromAddress(object_address); \
781 break; \
782 }
783 COMMON_REFERENCE_PATTERNS(COMMON_REFS_CASE)
784#undef COMMON_REFS_CASE
785 ONE_CASE_PER_SPACE(CODE_BACKREF_SERIALIZATION) {
786 int backref_space = (data & kSpaceMask);
787 // Can't use Code::cast because heap is not set up yet and assertions
788 // will fail.
789 Code* code_object =
790 reinterpret_cast<Code*>(GetAddressFromEnd(backref_space));
791 // Setting a branch/call to previously decoded code object from code.
792 Address location_of_branch_data = reinterpret_cast<Address>(current);
793 Assembler::set_target_at(location_of_branch_data,
794 code_object->instruction_start());
795 location_of_branch_data += Assembler::kCallTargetSize;
796 current = reinterpret_cast<Object**>(location_of_branch_data);
797 break;
798 }
799 ONE_CASE_PER_SPACE(CODE_REFERENCE_SERIALIZATION) {
800 int backref_space = (data & kSpaceMask);
801 // Can't use Code::cast because heap is not set up yet and assertions
802 // will fail.
803 Code* code_object =
804 reinterpret_cast<Code*>(GetAddressFromStart(backref_space));
805 // Setting a branch/call to previously decoded code object from code.
806 Address location_of_branch_data = reinterpret_cast<Address>(current);
807 Assembler::set_target_at(location_of_branch_data,
808 code_object->instruction_start());
809 location_of_branch_data += Assembler::kCallTargetSize;
810 current = reinterpret_cast<Object**>(location_of_branch_data);
811 break;
812 }
813 case EXTERNAL_REFERENCE_SERIALIZATION: {
814 int reference_id = source_->GetInt();
815 Address address = external_reference_decoder_->Decode(reference_id);
816 *current++ = reinterpret_cast<Object*>(address);
817 break;
818 }
819 case EXTERNAL_BRANCH_TARGET_SERIALIZATION: {
820 int reference_id = source_->GetInt();
821 Address address = external_reference_decoder_->Decode(reference_id);
822 Address location_of_branch_data = reinterpret_cast<Address>(current);
823 Assembler::set_external_target_at(location_of_branch_data, address);
824 location_of_branch_data += Assembler::kExternalTargetSize;
825 current = reinterpret_cast<Object**>(location_of_branch_data);
826 break;
827 }
828 case START_NEW_PAGE_SERIALIZATION: {
829 int space = source_->Get();
830 pages_[space].Add(last_object_address_);
Steve Block6ded16b2010-05-10 14:33:55 +0100831 if (space == CODE_SPACE) {
832 CPU::FlushICache(last_object_address_, Page::kPageSize);
833 }
Steve Blockd0582a62009-12-15 09:54:21 +0000834 break;
835 }
836 case NATIVES_STRING_RESOURCE: {
837 int index = source_->Get();
838 Vector<const char> source_vector = Natives::GetScriptSource(index);
839 NativesExternalStringResource* resource =
840 new NativesExternalStringResource(source_vector.start());
841 *current++ = reinterpret_cast<Object*>(resource);
842 break;
843 }
Leon Clarkee46be812010-01-19 14:06:41 +0000844 case ROOT_SERIALIZATION: {
845 int root_id = source_->GetInt();
846 *current++ = Heap::roots_address()[root_id];
847 break;
848 }
Leon Clarked91b9f72010-01-27 17:25:45 +0000849 case PARTIAL_SNAPSHOT_CACHE_ENTRY: {
850 int cache_index = source_->GetInt();
851 *current++ = partial_snapshot_cache_[cache_index];
852 break;
853 }
854 case SYNCHRONIZE: {
855 // If we get here then that indicates that you have a mismatch between
856 // the number of GC roots when serializing and deserializing.
857 UNREACHABLE();
858 }
Steve Blockd0582a62009-12-15 09:54:21 +0000859 default:
860 UNREACHABLE();
861 }
862 }
863 ASSERT_EQ(current, limit);
864}
865
866
867void SnapshotByteSink::PutInt(uintptr_t integer, const char* description) {
868 const int max_shift = ((kPointerSize * kBitsPerByte) / 7) * 7;
869 for (int shift = max_shift; shift > 0; shift -= 7) {
870 if (integer >= static_cast<uintptr_t>(1u) << shift) {
Andrei Popescu402d9372010-02-26 13:31:12 +0000871 Put((static_cast<int>((integer >> shift)) & 0x7f) | 0x80, "IntPart");
Steve Blockd0582a62009-12-15 09:54:21 +0000872 }
873 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000874 PutSection(static_cast<int>(integer & 0x7f), "IntLastPart");
Steve Blockd0582a62009-12-15 09:54:21 +0000875}
876
Steve Blocka7e24c12009-10-30 11:49:00 +0000877#ifdef DEBUG
Steve Blockd0582a62009-12-15 09:54:21 +0000878
879void Deserializer::Synchronize(const char* tag) {
880 int data = source_->Get();
881 // If this assert fails then that indicates that you have a mismatch between
882 // the number of GC roots when serializing and deserializing.
883 ASSERT_EQ(SYNCHRONIZE, data);
884 do {
885 int character = source_->Get();
886 if (character == 0) break;
887 if (FLAG_debug_serialization) {
888 PrintF("%c", character);
889 }
890 } while (true);
891 if (FLAG_debug_serialization) {
892 PrintF("\n");
893 }
894}
895
Steve Blocka7e24c12009-10-30 11:49:00 +0000896
897void Serializer::Synchronize(const char* tag) {
Steve Blockd0582a62009-12-15 09:54:21 +0000898 sink_->Put(SYNCHRONIZE, tag);
899 int character;
900 do {
901 character = *tag++;
902 sink_->PutSection(character, "TagCharacter");
903 } while (character != 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000904}
Steve Blockd0582a62009-12-15 09:54:21 +0000905
Steve Blocka7e24c12009-10-30 11:49:00 +0000906#endif
907
Steve Blockd0582a62009-12-15 09:54:21 +0000908Serializer::Serializer(SnapshotByteSink* sink)
909 : sink_(sink),
910 current_root_index_(0),
Andrei Popescu31002712010-02-23 13:46:05 +0000911 external_reference_encoder_(new ExternalReferenceEncoder),
Leon Clarkee46be812010-01-19 14:06:41 +0000912 large_object_total_(0) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000913 for (int i = 0; i <= LAST_SPACE; i++) {
Steve Blockd0582a62009-12-15 09:54:21 +0000914 fullness_[i] = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000915 }
916}
917
918
Andrei Popescu31002712010-02-23 13:46:05 +0000919Serializer::~Serializer() {
920 delete external_reference_encoder_;
921}
922
923
Leon Clarked91b9f72010-01-27 17:25:45 +0000924void StartupSerializer::SerializeStrongReferences() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000925 // No active threads.
926 CHECK_EQ(NULL, ThreadState::FirstInUse());
927 // No active or weak handles.
928 CHECK(HandleScopeImplementer::instance()->blocks()->is_empty());
929 CHECK_EQ(0, GlobalHandles::NumberOfWeakHandles());
Steve Blockd0582a62009-12-15 09:54:21 +0000930 // We don't support serializing installed extensions.
931 for (RegisteredExtension* ext = RegisteredExtension::first_extension();
932 ext != NULL;
933 ext = ext->next()) {
934 CHECK_NE(v8::INSTALLED, ext->state());
935 }
Leon Clarked91b9f72010-01-27 17:25:45 +0000936 Heap::IterateStrongRoots(this, VISIT_ONLY_STRONG);
Steve Blocka7e24c12009-10-30 11:49:00 +0000937}
938
939
Leon Clarked91b9f72010-01-27 17:25:45 +0000940void PartialSerializer::Serialize(Object** object) {
Leon Clarkee46be812010-01-19 14:06:41 +0000941 this->VisitPointer(object);
Leon Clarked91b9f72010-01-27 17:25:45 +0000942
943 // After we have done the partial serialization the partial snapshot cache
944 // will contain some references needed to decode the partial snapshot. We
945 // fill it up with undefineds so it has a predictable length so the
946 // deserialization code doesn't need to know the length.
947 for (int index = partial_snapshot_cache_length_;
948 index < kPartialSnapshotCacheCapacity;
949 index++) {
950 partial_snapshot_cache_[index] = Heap::undefined_value();
951 startup_serializer_->VisitPointer(&partial_snapshot_cache_[index]);
952 }
953 partial_snapshot_cache_length_ = kPartialSnapshotCacheCapacity;
Leon Clarkee46be812010-01-19 14:06:41 +0000954}
955
956
Steve Blocka7e24c12009-10-30 11:49:00 +0000957void Serializer::VisitPointers(Object** start, Object** end) {
Steve Blockd0582a62009-12-15 09:54:21 +0000958 for (Object** current = start; current < end; current++) {
959 if ((*current)->IsSmi()) {
960 sink_->Put(RAW_DATA_SERIALIZATION, "RawData");
961 sink_->PutInt(kPointerSize, "length");
962 for (int i = 0; i < kPointerSize; i++) {
963 sink_->Put(reinterpret_cast<byte*>(current)[i], "Byte");
964 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000965 } else {
Steve Blockd0582a62009-12-15 09:54:21 +0000966 SerializeObject(*current, TAGGED_REPRESENTATION);
Steve Blocka7e24c12009-10-30 11:49:00 +0000967 }
968 }
969}
970
971
Leon Clarked91b9f72010-01-27 17:25:45 +0000972Object* SerializerDeserializer::partial_snapshot_cache_[
973 kPartialSnapshotCacheCapacity];
974int SerializerDeserializer::partial_snapshot_cache_length_ = 0;
975
976
977// This ensures that the partial snapshot cache keeps things alive during GC and
978// tracks their movement. When it is called during serialization of the startup
979// snapshot the partial snapshot is empty, so nothing happens. When the partial
980// (context) snapshot is created, this array is populated with the pointers that
981// the partial snapshot will need. As that happens we emit serialized objects to
982// the startup snapshot that correspond to the elements of this cache array. On
983// deserialization we therefore need to visit the cache array. This fills it up
984// with pointers to deserialized objects.
Steve Block6ded16b2010-05-10 14:33:55 +0100985void SerializerDeserializer::Iterate(ObjectVisitor* visitor) {
Leon Clarked91b9f72010-01-27 17:25:45 +0000986 visitor->VisitPointers(
987 &partial_snapshot_cache_[0],
988 &partial_snapshot_cache_[partial_snapshot_cache_length_]);
989}
990
991
992// When deserializing we need to set the size of the snapshot cache. This means
993// the root iteration code (above) will iterate over array elements, writing the
994// references to deserialized objects in them.
995void SerializerDeserializer::SetSnapshotCacheSize(int size) {
996 partial_snapshot_cache_length_ = size;
997}
998
999
1000int PartialSerializer::PartialSnapshotCacheIndex(HeapObject* heap_object) {
1001 for (int i = 0; i < partial_snapshot_cache_length_; i++) {
1002 Object* entry = partial_snapshot_cache_[i];
1003 if (entry == heap_object) return i;
1004 }
Andrei Popescu31002712010-02-23 13:46:05 +00001005
Leon Clarked91b9f72010-01-27 17:25:45 +00001006 // We didn't find the object in the cache. So we add it to the cache and
1007 // then visit the pointer so that it becomes part of the startup snapshot
1008 // and we can refer to it from the partial snapshot.
1009 int length = partial_snapshot_cache_length_;
1010 CHECK(length < kPartialSnapshotCacheCapacity);
1011 partial_snapshot_cache_[length] = heap_object;
1012 startup_serializer_->VisitPointer(&partial_snapshot_cache_[length]);
1013 // We don't recurse from the startup snapshot generator into the partial
1014 // snapshot generator.
1015 ASSERT(length == partial_snapshot_cache_length_);
1016 return partial_snapshot_cache_length_++;
1017}
1018
1019
1020int PartialSerializer::RootIndex(HeapObject* heap_object) {
Leon Clarkee46be812010-01-19 14:06:41 +00001021 for (int i = 0; i < Heap::kRootListLength; i++) {
1022 Object* root = Heap::roots_address()[i];
1023 if (root == heap_object) return i;
1024 }
1025 return kInvalidRootIndex;
1026}
1027
1028
Leon Clarked91b9f72010-01-27 17:25:45 +00001029// Encode the location of an already deserialized object in order to write its
1030// location into a later object. We can encode the location as an offset from
1031// the start of the deserialized objects or as an offset backwards from the
1032// current allocation pointer.
1033void Serializer::SerializeReferenceToPreviousObject(
1034 int space,
1035 int address,
1036 ReferenceRepresentation reference_representation) {
1037 int offset = CurrentAllocationAddress(space) - address;
1038 bool from_start = true;
1039 if (SpaceIsPaged(space)) {
1040 // For paged space it is simple to encode back from current allocation if
1041 // the object is on the same page as the current allocation pointer.
1042 if ((CurrentAllocationAddress(space) >> kPageSizeBits) ==
1043 (address >> kPageSizeBits)) {
1044 from_start = false;
1045 address = offset;
1046 }
1047 } else if (space == NEW_SPACE) {
1048 // For new space it is always simple to encode back from current allocation.
1049 if (offset < address) {
1050 from_start = false;
1051 address = offset;
1052 }
1053 }
1054 // If we are actually dealing with real offsets (and not a numbering of
1055 // all objects) then we should shift out the bits that are always 0.
1056 if (!SpaceIsLarge(space)) address >>= kObjectAlignmentBits;
1057 // On some architectures references between code objects are encoded
1058 // specially (as relative offsets). Such references have their own
1059 // special tags to simplify the deserializer.
1060 if (reference_representation == CODE_TARGET_REPRESENTATION) {
1061 if (from_start) {
1062 sink_->Put(CODE_REFERENCE_SERIALIZATION + space, "RefCodeSer");
1063 sink_->PutInt(address, "address");
1064 } else {
1065 sink_->Put(CODE_BACKREF_SERIALIZATION + space, "BackRefCodeSer");
1066 sink_->PutInt(address, "address");
1067 }
1068 } else {
1069 // Regular absolute references.
1070 CHECK_EQ(TAGGED_REPRESENTATION, reference_representation);
1071 if (from_start) {
1072 // There are some common offsets that have their own specialized encoding.
1073#define COMMON_REFS_CASE(tag, common_space, common_offset) \
1074 if (space == common_space && address == common_offset) { \
1075 sink_->PutSection(tag + REFERENCE_SERIALIZATION, "RefSer"); \
1076 } else /* NOLINT */
1077 COMMON_REFERENCE_PATTERNS(COMMON_REFS_CASE)
1078#undef COMMON_REFS_CASE
1079 { /* NOLINT */
1080 sink_->Put(REFERENCE_SERIALIZATION + space, "RefSer");
1081 sink_->PutInt(address, "address");
1082 }
1083 } else {
1084 sink_->Put(BACKREF_SERIALIZATION + space, "BackRefSer");
1085 sink_->PutInt(address, "address");
1086 }
1087 }
1088}
1089
1090
1091void StartupSerializer::SerializeObject(
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001092 Object* o,
Leon Clarke888f6722010-01-27 15:57:47 +00001093 ReferenceRepresentation reference_representation) {
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001094 CHECK(o->IsHeapObject());
1095 HeapObject* heap_object = HeapObject::cast(o);
Leon Clarked91b9f72010-01-27 17:25:45 +00001096
1097 if (address_mapper_.IsMapped(heap_object)) {
Leon Clarkeeab96aa2010-01-27 16:31:12 +00001098 int space = SpaceOfAlreadySerializedObject(heap_object);
Leon Clarked91b9f72010-01-27 17:25:45 +00001099 int address = address_mapper_.MappedTo(heap_object);
1100 SerializeReferenceToPreviousObject(space,
1101 address,
1102 reference_representation);
1103 } else {
1104 // Object has not yet been serialized. Serialize it here.
1105 ObjectSerializer object_serializer(this,
1106 heap_object,
1107 sink_,
1108 reference_representation);
1109 object_serializer.Serialize();
1110 }
1111}
1112
1113
1114void StartupSerializer::SerializeWeakReferences() {
1115 for (int i = partial_snapshot_cache_length_;
1116 i < kPartialSnapshotCacheCapacity;
1117 i++) {
1118 sink_->Put(ROOT_SERIALIZATION, "RootSerialization");
1119 sink_->PutInt(Heap::kUndefinedValueRootIndex, "root_index");
1120 }
1121 Heap::IterateWeakRoots(this, VISIT_ALL);
1122}
1123
1124
1125void PartialSerializer::SerializeObject(
1126 Object* o,
1127 ReferenceRepresentation reference_representation) {
1128 CHECK(o->IsHeapObject());
1129 HeapObject* heap_object = HeapObject::cast(o);
1130
1131 int root_index;
1132 if ((root_index = RootIndex(heap_object)) != kInvalidRootIndex) {
1133 sink_->Put(ROOT_SERIALIZATION, "RootSerialization");
1134 sink_->PutInt(root_index, "root_index");
1135 return;
1136 }
1137
1138 if (ShouldBeInThePartialSnapshotCache(heap_object)) {
1139 int cache_index = PartialSnapshotCacheIndex(heap_object);
1140 sink_->Put(PARTIAL_SNAPSHOT_CACHE_ENTRY, "PartialSnapshotCache");
1141 sink_->PutInt(cache_index, "partial_snapshot_cache_index");
1142 return;
1143 }
1144
1145 // Pointers from the partial snapshot to the objects in the startup snapshot
1146 // should go through the root array or through the partial snapshot cache.
1147 // If this is not the case you may have to add something to the root array.
1148 ASSERT(!startup_serializer_->address_mapper()->IsMapped(heap_object));
1149 // All the symbols that the partial snapshot needs should be either in the
1150 // root table or in the partial snapshot cache.
1151 ASSERT(!heap_object->IsSymbol());
1152
1153 if (address_mapper_.IsMapped(heap_object)) {
1154 int space = SpaceOfAlreadySerializedObject(heap_object);
1155 int address = address_mapper_.MappedTo(heap_object);
1156 SerializeReferenceToPreviousObject(space,
1157 address,
1158 reference_representation);
Steve Blockd0582a62009-12-15 09:54:21 +00001159 } else {
1160 // Object has not yet been serialized. Serialize it here.
1161 ObjectSerializer serializer(this,
1162 heap_object,
1163 sink_,
1164 reference_representation);
1165 serializer.Serialize();
1166 }
1167}
1168
1169
Steve Blockd0582a62009-12-15 09:54:21 +00001170void Serializer::ObjectSerializer::Serialize() {
1171 int space = Serializer::SpaceOfObject(object_);
1172 int size = object_->Size();
1173
1174 if (reference_representation_ == TAGGED_REPRESENTATION) {
1175 sink_->Put(OBJECT_SERIALIZATION + space, "ObjectSerialization");
1176 } else {
1177 CHECK_EQ(CODE_TARGET_REPRESENTATION, reference_representation_);
1178 sink_->Put(CODE_OBJECT_SERIALIZATION + space, "ObjectSerialization");
1179 }
1180 sink_->PutInt(size >> kObjectAlignmentBits, "Size in words");
1181
Leon Clarkee46be812010-01-19 14:06:41 +00001182 LOG(SnapshotPositionEvent(object_->address(), sink_->Position()));
1183
Steve Blockd0582a62009-12-15 09:54:21 +00001184 // Mark this object as already serialized.
1185 bool start_new_page;
Leon Clarked91b9f72010-01-27 17:25:45 +00001186 int offset = serializer_->Allocate(space, size, &start_new_page);
1187 serializer_->address_mapper()->AddMapping(object_, offset);
Steve Blockd0582a62009-12-15 09:54:21 +00001188 if (start_new_page) {
1189 sink_->Put(START_NEW_PAGE_SERIALIZATION, "NewPage");
1190 sink_->PutSection(space, "NewPageSpace");
1191 }
1192
1193 // Serialize the map (first word of the object).
1194 serializer_->SerializeObject(object_->map(), TAGGED_REPRESENTATION);
1195
1196 // Serialize the rest of the object.
1197 CHECK_EQ(0, bytes_processed_so_far_);
1198 bytes_processed_so_far_ = kPointerSize;
1199 object_->IterateBody(object_->map()->instance_type(), size, this);
1200 OutputRawData(object_->address() + size);
1201}
1202
1203
1204void Serializer::ObjectSerializer::VisitPointers(Object** start,
1205 Object** end) {
1206 Object** current = start;
1207 while (current < end) {
1208 while (current < end && (*current)->IsSmi()) current++;
1209 if (current < end) OutputRawData(reinterpret_cast<Address>(current));
1210
1211 while (current < end && !(*current)->IsSmi()) {
1212 serializer_->SerializeObject(*current, TAGGED_REPRESENTATION);
1213 bytes_processed_so_far_ += kPointerSize;
1214 current++;
1215 }
1216 }
1217}
1218
1219
1220void Serializer::ObjectSerializer::VisitExternalReferences(Address* start,
1221 Address* end) {
1222 Address references_start = reinterpret_cast<Address>(start);
1223 OutputRawData(references_start);
1224
1225 for (Address* current = start; current < end; current++) {
1226 sink_->Put(EXTERNAL_REFERENCE_SERIALIZATION, "ExternalReference");
1227 int reference_id = serializer_->EncodeExternalReference(*current);
1228 sink_->PutInt(reference_id, "reference id");
1229 }
1230 bytes_processed_so_far_ += static_cast<int>((end - start) * kPointerSize);
1231}
1232
1233
1234void Serializer::ObjectSerializer::VisitRuntimeEntry(RelocInfo* rinfo) {
1235 Address target_start = rinfo->target_address_address();
1236 OutputRawData(target_start);
1237 Address target = rinfo->target_address();
1238 uint32_t encoding = serializer_->EncodeExternalReference(target);
1239 CHECK(target == NULL ? encoding == 0 : encoding != 0);
1240 sink_->Put(EXTERNAL_BRANCH_TARGET_SERIALIZATION, "ExternalReference");
1241 sink_->PutInt(encoding, "reference id");
1242 bytes_processed_so_far_ += Assembler::kExternalTargetSize;
1243}
1244
1245
1246void Serializer::ObjectSerializer::VisitCodeTarget(RelocInfo* rinfo) {
1247 CHECK(RelocInfo::IsCodeTarget(rinfo->rmode()));
1248 Address target_start = rinfo->target_address_address();
1249 OutputRawData(target_start);
1250 Code* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
1251 serializer_->SerializeObject(target, CODE_TARGET_REPRESENTATION);
1252 bytes_processed_so_far_ += Assembler::kCallTargetSize;
1253}
1254
1255
1256void Serializer::ObjectSerializer::VisitExternalAsciiString(
1257 v8::String::ExternalAsciiStringResource** resource_pointer) {
1258 Address references_start = reinterpret_cast<Address>(resource_pointer);
1259 OutputRawData(references_start);
1260 for (int i = 0; i < Natives::GetBuiltinsCount(); i++) {
1261 Object* source = Heap::natives_source_cache()->get(i);
1262 if (!source->IsUndefined()) {
1263 ExternalAsciiString* string = ExternalAsciiString::cast(source);
1264 typedef v8::String::ExternalAsciiStringResource Resource;
1265 Resource* resource = string->resource();
1266 if (resource == *resource_pointer) {
1267 sink_->Put(NATIVES_STRING_RESOURCE, "NativesStringResource");
1268 sink_->PutSection(i, "NativesStringResourceEnd");
1269 bytes_processed_so_far_ += sizeof(resource);
1270 return;
1271 }
1272 }
1273 }
1274 // One of the strings in the natives cache should match the resource. We
1275 // can't serialize any other kinds of external strings.
1276 UNREACHABLE();
1277}
1278
1279
1280void Serializer::ObjectSerializer::OutputRawData(Address up_to) {
1281 Address object_start = object_->address();
1282 int up_to_offset = static_cast<int>(up_to - object_start);
1283 int skipped = up_to_offset - bytes_processed_so_far_;
1284 // This assert will fail if the reloc info gives us the target_address_address
1285 // locations in a non-ascending order. Luckily that doesn't happen.
1286 ASSERT(skipped >= 0);
1287 if (skipped != 0) {
1288 Address base = object_start + bytes_processed_so_far_;
1289#define RAW_CASE(index, length) \
1290 if (skipped == length) { \
1291 sink_->PutSection(RAW_DATA_SERIALIZATION + index, "RawDataFixed"); \
1292 } else /* NOLINT */
1293 COMMON_RAW_LENGTHS(RAW_CASE)
1294#undef RAW_CASE
1295 { /* NOLINT */
1296 sink_->Put(RAW_DATA_SERIALIZATION, "RawData");
1297 sink_->PutInt(skipped, "length");
1298 }
1299 for (int i = 0; i < skipped; i++) {
1300 unsigned int data = base[i];
1301 sink_->PutSection(data, "Byte");
1302 }
1303 bytes_processed_so_far_ += skipped;
1304 }
1305}
1306
1307
1308int Serializer::SpaceOfObject(HeapObject* object) {
1309 for (int i = FIRST_SPACE; i <= LAST_SPACE; i++) {
1310 AllocationSpace s = static_cast<AllocationSpace>(i);
1311 if (Heap::InSpace(object, s)) {
1312 if (i == LO_SPACE) {
1313 if (object->IsCode()) {
1314 return kLargeCode;
1315 } else if (object->IsFixedArray()) {
1316 return kLargeFixedArray;
1317 } else {
1318 return kLargeData;
1319 }
1320 }
1321 return i;
1322 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001323 }
1324 UNREACHABLE();
Steve Blockd0582a62009-12-15 09:54:21 +00001325 return 0;
1326}
1327
1328
1329int Serializer::SpaceOfAlreadySerializedObject(HeapObject* object) {
1330 for (int i = FIRST_SPACE; i <= LAST_SPACE; i++) {
1331 AllocationSpace s = static_cast<AllocationSpace>(i);
1332 if (Heap::InSpace(object, s)) {
1333 return i;
1334 }
1335 }
1336 UNREACHABLE();
1337 return 0;
1338}
1339
1340
1341int Serializer::Allocate(int space, int size, bool* new_page) {
1342 CHECK(space >= 0 && space < kNumberOfSpaces);
1343 if (SpaceIsLarge(space)) {
1344 // In large object space we merely number the objects instead of trying to
1345 // determine some sort of address.
1346 *new_page = true;
Leon Clarkee46be812010-01-19 14:06:41 +00001347 large_object_total_ += size;
Steve Blockd0582a62009-12-15 09:54:21 +00001348 return fullness_[LO_SPACE]++;
1349 }
1350 *new_page = false;
1351 if (fullness_[space] == 0) {
1352 *new_page = true;
1353 }
1354 if (SpaceIsPaged(space)) {
1355 // Paged spaces are a little special. We encode their addresses as if the
1356 // pages were all contiguous and each page were filled up in the range
1357 // 0 - Page::kObjectAreaSize. In practice the pages may not be contiguous
1358 // and allocation does not start at offset 0 in the page, but this scheme
1359 // means the deserializer can get the page number quickly by shifting the
1360 // serialized address.
1361 CHECK(IsPowerOf2(Page::kPageSize));
1362 int used_in_this_page = (fullness_[space] & (Page::kPageSize - 1));
1363 CHECK(size <= Page::kObjectAreaSize);
1364 if (used_in_this_page + size > Page::kObjectAreaSize) {
1365 *new_page = true;
1366 fullness_[space] = RoundUp(fullness_[space], Page::kPageSize);
1367 }
1368 }
1369 int allocation_address = fullness_[space];
1370 fullness_[space] = allocation_address + size;
1371 return allocation_address;
Steve Blocka7e24c12009-10-30 11:49:00 +00001372}
1373
1374
1375} } // namespace v8::internal